Bc: get num list sum

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

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

but I can’t use cat input|cut -d " " -f 3 to get the number, how can I do this?

+5
source share
3 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 of grep, you can use cut

 $ cut -c 8- file 

or just awk

 $ awk '{print $NF}' file 

BUT if you can use awk you can summarize with awk

 $ awk '{total += $NF} END { print total }' file 
+11
source

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 this with sed or maybe awk, it's just a quick hack to add a trailing "0" to make bc happy. Run the different parts of the command separately to figure out what happens)

0
source

You can replace all spaces with + and pass the result to bc

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

0
source

Source: https://habr.com/ru/post/1413095/


All Articles