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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With