Home > OS >  How to add the elements in a for loop
How to add the elements in a for loop

Time:11-01

so basically my code looks through data and greps whatever it begins with, and so I've been trying to figure out a way where I'm able to add the those values.

the sample input is

35 45 75 76
34 45 53 55
33 34 32 21

my code:

for id in $(awk '{ print $1 }' < $3); do echo $id; done

I'm printing it right now to see the values but basically whats outputted is

35
34
33

I'm trying to add them all together but I cant figure out how, some help would be appreciated.

my desired output would be

103

CodePudding user response:

Lots of ways to do this, a few ideas ...

$ cat numbers.dat
35 45 75 76
34 45 53 55
33 34 32 21

Tweaking OP's current code:

$ sum=0
$ for id in $(awk '{ print $1 }' < numbers.dat); do ((sum =id)); done
$ echo "${sum}"
102

Eliminating awk:

$ sum=0
$ while read -r id rest_of_line; do sum=$((sum id)); done < numbers.dat
$ echo "${sum}"
102

Using just awk (looks like Aivean beat me to it):

$ awk '{sum =$1} END {print sum}' numbers.dat
102

CodePudding user response:

awk '{ sum  = $1 } END { print sum }'

Test:

35 45 75 76
34 45 53 55
33 34 32 21

Result:

102

(sum(35, 34, 33) = 102, that's what you want, right?)

Here is the detailed explanation of how this works:

  1. $1 is the first column of the input.
  2. sum is the variable that holds the sum of all the values in the first column.
  3. END { print sum } is the action to be performed after all the input has been processed.

So the awk program is basically summing up the first column of the input and printing the result.


This answer was partially generated by Davinci Codex model, supervised and verified by me.

  • Related