Input file:
$ cat /tmp/file.txt
286
255564800
609
146
671290
Required: Add (Sum) all the numbers present in the above file.
Way#1: This is supposed to be the most popular way of doing an addition of numbers present in a particular field of a file.
$ awk '{s+=$0} END {print s}' /tmp/file.txt
256237131
Way#2: Using UNIX/Linux 'paste' command and 'bc'
$ paste -sd+ /tmp/file.txt
286+255564800+609+146+671290
$ paste -sd+ /tmp/file.txt | bc
256237131
Way#3: Using UNIX/Linux 'tr' command and 'bc'
$ tr -s '\n' '+' < /tmp/file.txt
286+255564800+609+146+671290+
$ echo $(tr -s '\n' '+' < /tmp/file.txt)
286+255564800+609+146+671290+
#Since there's an extra '+' at end of above output, echo an additional '0' like this
$ echo $(tr -s '\n' '+' < /tmp/file.txt)0
286+255564800+609+146+671290+0
$ echo $(tr -s '\n' '+' < /tmp/file.txt)0 | bc
256237131
Way#4: Same as above but doing the arithmetic without using 'bc'
$ printf "%d\n" $(( $(tr -s '\n' '+' < /tmp/file.txt) 0 ))
256237131
Way#5: Using sed and 'bc'
$ sed 's/$/+/' /tmp/file.txt
286+
255564800+
609+
146+
671290+
$ echo $(sed 's/$/+/' /tmp/file.txt) 0
286+ 255564800+ 609+ 146+ 671290+ 0
$ echo $(sed 's/$/+/' /tmp/file.txt) 0 | bc
256237131
Way#6 : or a basic bash script using for loop
sum=0
for num in $(cat /tmp/file.txt)
do
((sum+=num))
done
echo $sum
Way#7: Using python
>>> sum = 0
>>> lines = open("/tmp/file.txt", "r").readlines()
>>> lines
['286\n', '255564800\n', '609\n', '146\n', '671290\n']
>>> for line in lines:
... sum+=eval(line)
...
>>> sum
256237131
Related posts:
- 'Sum of' and 'group by' using awk
- Sum using awk substr function in bash
- Bash 'while loop' sum issue explained
- 'Exponential' value in awk sum output
- Python - adding numbers in a list

