Read from file and add numbers

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

How to add these numbers and get their amount.

+7
bash add
source share
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 Introduction to Programming, Arithmetic Evaluation Section

+7
source share

A Bash is just ( cat ) a variation of MYYN's answer.

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

Also note the simpler arithmetic operator.

+3
source share

only one awk command is executed. It will not break when you have decimal numbers to add as well.

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

Alternative to 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 is 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 the Dave Jarvis solution is especially neat!

0
source share

All Articles