Count the sum of each column in a file

In a file with different number of columns delimited by space ' ', How to count the sum of the columns. An example would show the need:

File A:

1 2 
2 3
4 5 6 
1 1 1 5

Then the output would be:

  • for column 1 (1+2+4+1)=8
  • for column 2 is 11
  • for column 3 is 7
  • for column 4 is 5

Solution 1:

Using awk

awk '{for (i=1;i<=NF;i++) sum[i]+=$i;}; END{for (i in sum) print "for column "i" is " sum[i];}' FileA
for column 1 is 8
for column 2 is 11
for column 3 is 7
for column 4 is 5

Solution 2:

Use numsum for that task and separate between data processing and output the results.

Install num-utils, we need numsum

sudo apt-get install num-utils

And start with

numsum -c <your_file_name>

Example

$ cat "File A"
1 2 
2 3
4 5 6 
1 1 1 5

$ numsum -c "File A"
8 11 7 5

or with your desired format:

$ numsum -c "File A" | awk '{for(i=1;i<=NF;i++) {print "for column "i" is "$i}}'
for column 1 is 8
for column 2 is 11
for column 3 is 7
for column 4 is 5

from man numsum

-c      Print out the sum of each column.

examples from man numsum

EXAMPLES

   Add up the 1st, 2nd and 5th columns only.

       $ numsum -c -x 1,2,5 columns
       15 40 115

   Add up the rows of numbers of a file.

        $ numsum -r columns
        55
        60
        65
        70
        75