How to Sum a column in AWK?

You could sum the column 57 of your file, and print it using

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

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.

Tags:

Unix

Awk