Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bc: get the sum of a list of num

Tags:

unix

bc


Jack   10
J      10 
A      20 
Lu cal 20
A bc U 20

I want to get the sum of these nums: 10+10+20+20+20 = 80

but I can't use cat input|cut -d " " -f 3 to get the num, how can I do it?

like image 762
NOrder Avatar asked May 18 '12 03:05

NOrder


People also ask

How will you find the sum of all numbers in a file in Linux?

The most basic approach is to open the file and read the contents and then calculate the sum of all the numbers by making use of the do while loop.


1 Answers

You can use grep + paste + bc

$ grep -oE '[0-9]+' file
10
10
20
20
20

$ grep -oE '[0-9]+' file | paste -s -d + - 
10+10+20+20+20

$ grep -oE '[0-9]+' file | paste -s -d + - | bc
80

instead grep, you can use cut

$ cut -c 8- file

or just awk

$ awk '{print $NF}' file

BUT if you can use awk, you can sum using awk

$ awk '{total += $NF} END { print total }' file
like image 59
Tiago Peczenyj Avatar answered Oct 10 '22 14:10

Tiago Peczenyj