Sum Column in Linux

Comments Off on Sum Column in Linux

Sum column in Linux  is very easy  and you can do it by a single command.  If you have a file with multiple columns and you need to quickly get the total of a column in command line in  Linux , the easiest way is to use AWK .   Consider you have a file name test.txt . The file content is space or tab separated.

 

1 2 3
3 4 5
5 6 9
7 8 10

Consider, you would like to sum second column .  The command is

awk 'BEGIN{sum=0}{sum=sum+$2}END{print sum}' test.txt

The $2 actually defines which column you would like to sum. If you would like to sum the third column the command will be

awk 'BEGIN{sum=0}{sum=sum+$3}END{print sum}' test.txt

If your file is not space or tab separated the command will be little different . As example your file is CSV file or comma separated and its name is test2.csv and you would like to sum third column

1,2,3
3,4,5
5,6,9
7,8,10
awk 'BEGIN{FS=",";sum=0}{sum=sum+$3}END{print sum}' test2.csv

You have to just put FS =”,” syntax.   That means any field separator rather than space or tab you have to use FS=”field separator” syntax under begin section of awk.

Now, consider your file (test2.csv) has header row and you want to skip that line

C1,C2,C3
1,2,3
3,4,5
5,6,9
7,8,10

To sum third column , the command will be

awk 'BEGIN{FS=",";sum=0}{if(NR>1)sum=sum+$3}END{print sum}' test2.csv

So, sum column in Linux is an one command task and I hope the above tutorial would be helpful for everyone.