I have text file with entries like 123 112 3333 44 2
How to add these numbers and get the sum of these.
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
.