Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Sum a column in AWK? [duplicate]

Tags:

My file is delimited by a comma which gives 64 columns. I extracted the field as shown below:

awk '{split($0,a,",");  print a[57]}' 

How can I compute the sum of the values in columns 57 with my command?

like image 319
Ajo Avatar asked Mar 06 '15 18:03

Ajo


Video Answer


1 Answers

The split seems unnecessary here, especially considering you're using awk, which is made for field based processing. If your file is truly comma-separated, the following code seems much simpler, IMO:

awk -F',' '{sum+=$57;} END{print sum;}' file.txt 

For example, given the following input:

    ~$ cat testawk.txt     a,a,aa,1     a,a,aa,2     d,d,dd,7     d,d,dd,9     d,dd,d,0     d,d,dd,23     d,d,dd,152     d,d,dd,7     d,d,dd,5     f2,f2,f2,5.5 

We can get the sum like:

~$ awk -F',' '{sum+=$4;}END{print sum;}' testawk.txt    216.5 

The -F',' tells awk that the field separator for the input is a comma.

The {sum+=$4;} adds the value of the 4th column to a running total.

The END{print sum;} tells awk to print the contents of sum after all lines are read.

like image 56
zzevannn Avatar answered Sep 21 '22 09:09

zzevannn