Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read from file and add numbers

Tags:

bash

add

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

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

like image 745
Laks Avatar asked Apr 03 '10 20:04

Laks


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

like image 194
miku Avatar answered Nov 16 '22 21:11

miku


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.

like image 35
Dennis Williamson Avatar answered Nov 16 '22 21:11

Dennis Williamson


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
like image 21
ghostdog74 Avatar answered Nov 16 '22 21:11

ghostdog74