Tag Archives: awk

Calculating sum of numbers in the shell

More than one time I wanted to sum up numbers in the shell.

Imagine a command producing a list of numbers like this:


$ ...
42
23
966
1764
529
4711

Now calculating the sum of these numbers is not trivial. Using tools like bc or calc directly is not possible because you would need to put plus signs between the numbers first. So you could probably replace all ‘\n’ with ‘+’ with tr — but not the last one as that would lead to a syntax error later. Or as an alternative you could write a long shell construct with while read ... etc. In short this is just getting way too complicated for such a simple task.

Here is the simple solution in awk:


$ ... | awk 'BEGIN {total = 0} {total += $1} END {print total}'
8035