How to perform addition on a set of values from a file in bash script

By | June 22, 2017
How to perform addition on a set of values from a file in bash script

How to perform addition on a set of values from a file in bash script

How to perform addition on a set of values from a file in bash script

Every Unix Administrator has had this at some point… have written a script that extracts multiple rows with values in each column that you want to add up to get the total….

And every Unix Administrator will have written a 4-10 line loop script using pure bash or an awk script to add them up.

Well… here is a solution to do it all on 1 short line !!!

First off you need to have ‘bc’ installed on your server (it wasnt on my Centos 6 server), so install it like this –

yum install bc

bc is a basic calculator. So to test this you now need a file of data –

[root ~]# cat m2
1
12
5
36
100
[root ~]#

Simple enough file, so now the magic 1 liner to add it up…

[root ~]# cat m2 | paste -sd+ - | bc
154
[root ~]#

Want to see what its doing? Remove the ‘bc’ and you can see what the paste bit does –

[root ~]# cat m2 | paste -sd+ -
1+12+5+36+100
[root ~]#

So its taken all of your input and added + delimiter between each value, then piped the output to ‘bc’

Need it to handle decimal places? No problem create a file and add some decimal places in there –

[root ~]# cat m2
1
2.81
3
3.1
4
[root ~]#

[root ~]# cat m2 | paste -sd+ - | bc
13.91
[root ~]#

Obviously this was a very simple example, you can just as easily use grep and cut to get specific data and columns from a more complicated input file to achieve the same outcome

Check out -  How to solve Wordpress login hack attempts

Hope this has helped you (or made you wonder how many times you had created some loop to add it all up manually with a large amount of additional code!)

Oh well, as a Unix Administrator there is always something new to learn, and something is only easy if you know how !!

The journey continues….

If you found this step-by-step tutorial useful then share it to your friends !

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.