Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
    
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
up vote 5 down vote accepted

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

share|improve this answer

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.

share|improve this answer

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
share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .