user3624000 user3624000 - 6 months ago 17
Bash Question

How to add all values in a certain column?

I want to add all the 3rd fields from each line and produce the result.

Below is the way I solved the problem

sum=0
grep '2016Feb' input.txt|awk -F\- '{print $3}'|while read LINE; do
sum = $(expr $sum + $LINE)
done
echo $sum


Is there a better way of solving the problem than my code? Possible a command that solves the problem @ command line itself?

For a file like:

$ cat input.txt
Feb2016-2016-110
Feb2016-2016-20
Feb2016-2016-220
Feb2016-2016-140
Feb2016-2016-100


The output is:
590
.

Answer

Just set the field separator to the dash and sum the third column:

$ awk -F- '{sum+=$3} END{print sum+0}' file
590                               ^^
#                     in case there are no matching lines, print 0

Since it looks like you are just counting those lines that contain the text "Feb2016", you can also add a filter:

awk -F- '/Feb2016/{sum+=$3} END{print sum+0}' file
#        ^^^^^^^^^
#        just on lines containing the string "Feb2016"
Comments