2

Using nawk, how to sum all numbers in $1, $2, and $3 fields?

8     6     2

7     3     5

1     9     4

I want the result to be sum = 45

1
  • I had a comment, realized the question was across all. Can it be a bash script or do you want a one-liner?
    – nerdwaller
    Oct 31 '12 at 15:29
5

nawk 'BEGIN { sum=0; } {sum += $1 + $2 + $3;} END { printf "%d\n", sum } ' a.in

5

using awk:

awk '{x+=$0;}END{print x}' RS="[ \n]"  file

This will work irrespective of the number of rows or columns. By using the record separator(RS) as space or a newline, every value is split into a separate line, and hence can be easily added.

0

You could also go with coreutils and bc:

<file head -c-1 | tr ' \n' '++'; echo) | bc

If some columns should be omitted, e.g. if the input is like this:

A 8 6 2
B 7 3 5
C 1 9 4

cut can select the wanted ones:

<file cut -d' ' -f2- | head -c-1 | tr ' \n' '++'; echo) | bc

Output in both cases:

45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.