Using awk to sum/count a column of numbers.

cat count.txt | awk '{ sum+=$1} END {print sum}'
Takes a input file (count.txt) that looks like: 1 2 3 4 5 It will add/sum the first column of numbers.

19
By: duxklr
2009-03-16 00:22:13

2 Alternatives + Submit Alt

What Others Think

@unixmonkey2316 We love awk but save the cat's! :-) < count.txt awk '{sum+=$1} END {print sum}'
mpb · 634 weeks and 6 days ago
Or: printf '%s\n' $(( $(paste<infile -sd+) ))
radoulov · 634 weeks and 6 days ago
echo test | fold -w 1 t e s t
OJM · 634 weeks and 5 days ago
@myself: silly me, sorry for the noise, all wrong.
OJM · 634 weeks and 5 days ago
How about: awk '{ sum+=$1} END {print sum}' count.txt Another useless use of cat.
rjc · 634 weeks and 5 days ago
@rjc those who don't understand awk have redundancies all over the place. 'grep foo | awk', 'cat bar | awk', etc.
atoponce · 634 weeks and 4 days ago
cat test.log | awk -F, '{sum+=$1} END{print sum}' But my input file is 1,www.zzzzzzzzzzzzz/,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,bro.jpg&h=70&w=105&usg=AFrqEzeDZa4qbOTgz8UtMnCmRSVWz6Jccg","LG-KP500 Teleca/WAP2.0 MIDP-2.0/CLDC-1.1","","image/jpeg" 2,www.t.com Iam getting error : records number 1 has too many feilds... Can you give me the solutions
Jay · 557 weeks and 6 days ago
Try this: awk -F ';' '{sum+=$NF} END {print "total:" sum}' filename In your .awk file you can try: BEGIN { FS = ";" } {sum+=$NF} END {print "total:" sum}
mveera · 133 weeks ago

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this?

commandlinefu.com is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands



Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.

» http://twitter.com/commandlinefu
» http://twitter.com/commandlinefu3
» http://twitter.com/commandlinefu10

Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: