Tuesday, June 23, 2015

How to calculate sum for a column with awk

Use awk to count the sum for column 4, add up the numbers of the field 4 to the variable 'sum'. Print sum with END condition.
Lets say that you have a header in your file, to avoid using the header use NR>2 as a condition to start adding to the sum variable when the number of records is 2. 

awk 'NR>2 {sum += $4 } END { print sum }' file.txt

To do this for multiple columns use two or more variables:

awk 'NR>2 {sum += $2; sum2 +=$3} END { print sum "\t" sum2 }' file.txt

No comments:

Post a Comment