Read from File and Add Numbers

I have text file with entries like 123 112 3333 44 2

How to add these numbers and get the sum of these.

1

4 Answers

Example:

$ cat numbers.txt
123 112 3333 44 2

$ SUM=0; for i in `cat numbers.txt`; do SUM=$(($SUM + $i)); done; echo $SUM
3614

See also: Bash Programming Introduction, section on arithmetic evaluation

Another way would be to use bc, an arbitrary precision calculator language:

$ echo '123 112 3333 44 2' | tr ' ' '\n' | paste -sd+ | bc
3614

Paste usually works on lines, so we need tr.

0

A Bash-only (no cat) variation on MYYN's answer.

sum=0; for i in $(<number_file); do ((sum += i)); done; echo $sum

Also, note the simpler arithmetic statement.

1

just one awk command does it. It doesn't break when you have decimals to add as well.

awk '{for(i=1;i<=NF;i++)s+=$i}END{print s}' file

Alternatively in Awk

echo "123 112 3333 44 2" | awk 'BEGIN {sum=0} {for(i=1; i<=NF; i++) sum+=$i } END {print sum}'

Or if it's in a file

cat file.txt | awk 'BEGIN {sum=0} {for(i=1; i<=NF; i++) sum+=$i } END {print sum}'

I find Awk much easier to read/remember. Although "Dave Jarvis" solution is particular neat!

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest