tags:

views:

67

answers:

5

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

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

+3  A: 

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

The MYYN
won't work if there are decimals.
ghostdog74
+2  A: 

If you don't absolutely need to use bash strings, use the command line utilities sed and bc:

sed numbers.txt -e 's/ /+/g' | bc

For multiple spaces:

sed numbers.txt -e 's/[[:space:]]\+/+/g' | bc
Dave Jarvis
yeah, looks more concise than 'for ... do .. etc'
The MYYN
These output totals per line (which may be desirable) rather than per whole file. It fails if there are leading or trailing spaces (or `[[:space:]]`), but that could easily be fixed: `sed numbers.txt 's/^[[:space:]]\+//;s/[[:space:]]$//;s/[[:space:]]\+/+/g' | bc`
Dennis Williamson
A: 

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.

Dennis Williamson
for OP's sample data, yes it works. But not when decimal numbers/floats are involved.
ghostdog74
"with entries like"
Dennis Williamson
A: 

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!

Jamie
no need for cat.
ghostdog74
A: 

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
ghostdog74