Sum a column of numbers from unix command line

Ever have some kind of text file or command output where you want to just get a sum of the numbers presented?  If it’s a single column, just pipe it to this:

awk '{ sum += $1 } END { print sum }'

I’m no expert with awk so I often use cut to work on the input rather than doing fancy things with awk and sed to manipulate the data on the inbound side.  For example, I have a text file that shows something like this:

variable : server_name : 10
variable : server_name : 20
variable : server_name : 30

and I wanted to know the sum of the third column.  So:

 cat data.txt | cut -f 3 -d ':' | awk '{ sum += $1 } END { print sum }'

One Reply to “Sum a column of numbers from unix command line”

Leave a Reply to Afraz Ahmed Cancel reply

Your email address will not be published. Required fields are marked *