awk : find sum of a column

January 24th, 2013 § 0 comments

Recently I had a situation that I need to find the sum of the values of a particular column in a tab seperated file. Using Excel/Libre office will be too expensive since it contains around > 40K rows. The same file looks like,
sample.txt

A        10 
B        20 
C        30 
D        40 
E        50 
F        60

Here I need to find the sum of second column. For me easy way find is writing a awk script. Here it is

cat sample.txt | awk -F"\t" '{ sum+=$2} END {print sum}'

Here `-F` option will notify awk that imput is a tab seperated file. So the awk will divide the columns based on tabs(\t).

$2 is the column number which we need to find the sum. Here it is $2 since we are summing second column. if it is first column then it should be replaced with $1.

The command outputs  210.

Thanks.

Revath S Kumar [RSK]

- Rubyist / JavaScripter - Yeoman Team member - Open source enthusiast - Blogger @ PHPRepo and http://blog.revathskumar.com - Coder @ Whatznear - Google fanboy - jQuery lover

More Posts - Website - Twitter - Facebook - LinkedIn - Pinterest - Google Plus - YouTube