0

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

3 Answers 3

1

This will also do the job:

awk -F'*' '{i+=$1*$2} END{print i}' count.txt
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.