Hi I need to get the sum of each and every column in a file, needs to be flexible to as many columns as are in any given file

currently I use:

awk '{for (i=1;i<=NF;i++) sum[i]+=$i;}; END{for (i in sum) print sum[i];}'

This however, only gives me the sum of the first column, which i could obviously loop, but i would prefer something simpler.

Any ideas/answers?

  • 2
    No, that will pretty definitely give you the sum of each column. – DopeGhoti Apr 25 '17 at 20:20
  • That's what i thought, but for some reason its only providing the sum of .... AHHHHH for crying out loud!! its because i haven't set awk with comma delimited!! – Giles Apr 25 '17 at 20:25

It does give you the sum of every column, but in one column (provided that the data is whitespace-separated):

$ cat data.in
1 2
3 4
5 6

$ awk '{ for (i=1;i<=NF;i++) sum[i]+=$i } END { for (i in sum) print sum[i] }' data.in

So it's a matter of not outputting a newline between each sum.

$ awk '{ for (i=1;i<=NF;i++) sum[i]+=$i } END { for (i in sum) printf("%d ", sum[i]); printf("\n") }' data.in
12 9

The printf() function takes a format string. The %d is the formatting string for an integer (use %f for floats), and the following space will also be outputted after the integer. We then finish with outputting an explicit newline after the loop.

Another way to solve it, using the ORS ("Output Record Separator") variable:

$ awk 'BEGIN { ORS=" " } { for (i=1;i<=NF;i++) sum[i]+=$i } END { for (i in sum) print sum[i]; printf("\n") }' data.in
12 9

Also see Dave Thompson's insightful warning in comments below about the ordering of keys in Awk's associative arrays (which are not guaranteed to be sorted).

  • Although my question was incorrect due to my foolish overlook, you did also suss the fault and provide a better output. Thanks for the quick response and good answer – Giles Apr 25 '17 at 20:32
  • awk for(sub in ary) yields the subscripts in arbitrary order that usually will not be their numeric order, except GNU awk >= 4 with PROCINFO["sorted_in"] set appropriately; use for(i=1; i in a; i++) instead. – dave_thompson_085 Apr 26 '17 at 6:13
perl -lane '$sum[$_] += $F[$_] for 0..$#F; END {print join $", @sum}' data.in

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.