I needed to sum up some shopping expenses.
It looked like a problem that should have already been solved, so using a search engine I stumbled upon this Stack-Overflow question’s answers.
I’ve found it really smart and simple, so I thought to write something in here.
The answers are pretty good explaining in details how the thing works, and of course you can always use man
to know more about a program you don’t know, especially with standard commands like cut
or paste
.
It’s a good idea to read the manual entry of a command, I usually learn something new each time.
The suggested algorithm works like this:
- Get the input numbers each in single row using
cut
if the input involves more than a field per row - concatenate each number with
+
as a separator into a single row using thepaste
command - pipe the expression to
bc
'sstdin
to execute it and print the result tostdout
.
The input being text can come from a file, the keyboard, another program or a machine. The output it’s text too, so you can copy it or pipe it into a file.
I’ve modified it to fit my use case like this:
cat | paste -sd+ | bc
This uses cat
to read the numbers from stdin
until CTRL-D
is entered, the rest is pretty much the same.
The cool thing is you can enter also expressions and bc
will evaluate them and return the sum.
So the following works as expected:
~ $ cat | paste -sd+ | bc
1
(2*3)
-8
-1
The last number (-1
) is the result printed by bc
.
So:
1 + 6 - 8 = 7 - 8 = -1
It’s nice especially for expense tracking and calculation where you buy for 3 pasta packs and you can just write (0.99*3)
instead of 0.99
three times.