I am looking for a command that will accept as input multiple lines of text, each line containing a single integer, and output the sum of these integers.
As a bit of background, I have a log file which includes timing measurements, so through grepping for the relevant lines, and a bit of sed
reformatting I can list all of the timings in that file. I'd like to work out the total however, and my mind has gone blank as to any command I can pipe this intermediate output to in order to do the final sum. I've always used expr
in the past, but unless it runs in RPN mode
I don't think it's going to cope with this (and even then it would be tricky).
What am I missing? Given that there are probably several ways to achieve this, I will be happy to read (and upvote
) any approach that works, even if someone else has already posted a different solution that does the job.
Related question: Shortest command to calculate the sum of a column of output on Unix? (credits @Andrew)
Update: Wow, as expected there are some nice answers here. Looks like I will definitely have to give awk
deeper inspection as a command-line tool
in general!
Plain bash:
The one-liner version in Python:
Note that negative numbers prefixed with minus sign should be translated for
dc
, since it uses_
prefix rather than-
prefix for that. For example, viatr '-' '_' | dc -f- -e '...'
.Edit: Since this answer got so many votes "for obscurity", here is a detailed explanation:
The expression
[+z1<r]srz1<rp
does the following:As pseudo-code:
To really understand the simplicity and power of
dc
, here is a working Python script that implements some of the commands fromdc
and executes a Python version of the above command:Alternative pure Perl, fairly readable, no packages or options required:
C++ (simplified):
SCC project - http://volnitsky.com/project/scc/
SCC is C++ snippets evaluator at shell prompt
BASH solution, if you want to make this a command (e.g. if you need to do this frequently):
Then usage: