bc: get the sum of a list of num
Asked Answered
B

3

8

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?

Boulanger answered 18/5, 2012 at 3:16 Comment(1)
The digits seem to start in column 8 if you're supposed to use cut; that should be a hint to get you going. You don't need cat either. You might need to use awk to do the summing, or sed to insert necessary extra characters.Clearway
D
23

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
Declare answered 18/5, 2012 at 3:38 Comment(0)
J
1

Assuming your file is called input.txt:

echo $(sed 's/[^0-9]*\([0-9]*\).*/\1+/' input.txt) '0' | bc

(I'm sure there is a more elegant way to do it with sed or perhaps awk, this is just a quick hack to add a terminating '0' to make bc happy. Run different parts of the command separately to figure out what's going on)

Jujube answered 18/5, 2012 at 3:29 Comment(0)
R
0

You could replace all whitespace with a + and pipe the result to bc

echo "5 6 2" | sed -E -e 's/\s+/+/g' | bc

Ranna answered 4/10, 2019 at 3:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.