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.

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 · 688 weeks ago
Or: printf '%s\n' $(( $(paste<infile -sd+) ))
radoulov · 688 weeks ago
echo test | fold -w 1 t e s t
OJM · 688 weeks ago
@myself: silly me, sorry for the noise, all wrong.
OJM · 688 weeks ago
How about: awk '{ sum+=$1} END {print sum}' count.txt Another useless use of cat.
rjc · 688 weeks ago
@rjc those who don't understand awk have redundancies all over the place. 'grep foo | awk', 'cat bar | awk', etc.
atoponce · 687 weeks and 6 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, Iam getting error : records number 1 has too many feilds... Can you give me the solutions
Jay · 611 weeks 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 · 186 weeks and 1 day ago
seofox · 26 weeks and 3 days ago ????? ??? ????? ???? SEO ????? ????? ????? ???? ????? ????? ??? ???? ???? ??????? Search Engine Optimization ??? ????? ??????????? ?? ????? ?????????? ????? ????? ?? ????
seofox · 16 weeks and 1 day ago
seofox · 14 weeks and 6 days 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? 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.


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: