Reputation: 319
How can I get the sum of the following number? They are getting multiplied before getting added.
Input File (count.txt)
2*4
2*1
3*1
3*1
2*1
2*1
Command I am using:
( echo 0 ; sed 's/$/ +/' count.txt; echo p ) | dc.
The Sum I am getting is 343 which is not correct. I am expecting 20 as sum.
2*4
2*1
3*1
3*1
2*1
2*1
Sum: 20 (Multiplication and then sum for each line)
Any ideas?
Thanks, Raj
Upvotes: 0
Views: 215
Reputation: 5658
This will also do the job:
awk -F'*' '{i+=$1*$2} END{print i}' count.txt
Upvotes: 1
Reputation: 1952
This should do the job:
cat count.txt | tr \\n \+ | sed 's/$/\n/' | bc
be sure that there's no new line at the end of file, otherwise you must modify the sed expression.
Upvotes: 1
Reputation: 22562
cat count | while read line; do echo $(($line)); done | awk '{i+=$1} END {print i}'
This is the best solution I could come up with, hope it helps.
Upvotes: 0