How can I quickly sum all numbers in a file?

Mark Roberts picture Mark Roberts · Apr 24, 2010 · Viewed 157.2k times · Source

I have a file which contains several thousand numbers, each on it's own line:

34
42
11
6
2
99
...

I'm looking to write a script which will print the sum of all numbers in the file. I've got a solution, but it's not very efficient. (It takes several minutes to run.) I'm looking for a more efficient solution. Any suggestions?

Answer

Ayman Hourieh picture Ayman Hourieh · Apr 24, 2010

You can use awk:

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