Shell command to sum integers, one per line?
Let say I want to add X numbers from a file :
For Example : file num.txt contain 4 numbers, now we want to add (sum) of all number from that file.
[root@amit ~]# cat num.txt
637
39
1180
2788
Let say I want to add X numbers from a file :
For Example : file num.txt contain 4 numbers, now we want to add (sum) of all number from that file.
[root@amit ~]# cat num.txt
637
39
1180
2788
Solution 1 :
[root@amit ~]# sum=0; while read num ; do sum=$(($sum + $num)); done < num.txt ; echo $sum
4644
Solution 2 :
[root@amit ~]# awk '{s+=$1} END {print s}' num.txt
4644
Solution 3 :
[root@amit ~]# perl -nle '$sum += $_ } END { print $sum' num.txt
4644
Solution 4 : same as Solution 2 (used "sum" instead of "s")
[root@amit ~]# awk '{ sum += $1 } END { print sum }' num.txt
4644
I like how a simple script like this could be modified to add up a second column of data just by changing the $1 to $2
Solution 5 :
[root@amit ~]# dc -f num.txt -e '[+z1<r]srz1<rp'
4644
This is really very helpful to sum (add) all number from a file by using AWK, DC, PERL, and SUM command.