Saturday, July 14, 2012

Bash syntax to calculate sum list of numeric values in a file

Lets say you have a file which consists list of Numeric values and wish to add the total sum of all the numeric values. The bash syntax would be:
sum=0; for i in `cat filename.txt`; do sum=$(( $sum + $i )); done; echo $sum
(or)
declare -i sum=0; for i in `cat filename.txt`; do sum+=$i; done; echo $sum

No comments:

Post a Comment

Popular Posts

About Me

My photo
I have started this blog to share my work experience and spread some smart solutions on Linux to Internet community. I'm hoping more people will get benefited from this blog. Brief about me: I have 14+ years experience working as System Admin and currently work with VMware.