5 different command methods to get the sum of all numbers in a file

Let's say we have a sample file with the following content:
 5  
 7  
 8  

Here are the different unix command methods to get the sum of the file content:

1. Use awk

We just need to add the numbers respectively to the variable x then print out the result once the END of the file is reached
 awk '{x+=$0}END{print x}' file  



2. Use paste and bc

I've written an article about the 'bc' command before and here we can use paste and bc to do the task.
 paste -s -d"+" file | bc  

The "-s" option of the paste command joins all the lines of a file. The "-d" option is for choosing the delimiter with which the lines are to be joined. At the end, we will have "5+7+8" for the bc command to give the result.


3. Use perl

The way we use perl will be similar to that of 'awk'. With perl, we will use $_ to indicate the current line of the file, as $0 with awk. Once the end of the file is reached, the final value of the variable x will be printed:
 perl -lne '$x+=$_; END{print $x;}' file  


4. Use sed and bc

We here use sed just like paste. We will join all the lines and separate the numbers with "+" . So the sed command will give us "5+7+8" and the bc command will give us the needed result.
 sed -e :a -e 'N;s/\n/+/;ta' file | bc  


 
5. Use sed and echo

We can use the echo command to do the addition instead of the bc command. 
 echo $((`sed '$!s/$/+/' file | tr '\n' ' '`))  
We use the sed command to add a "+" at the end of each line, we also use the 'tr' command to remove each new line and the echo command will do the final task of addition.


About the author: Neil is a Linux aficionado and SEO expert. He is currently running Hosting Tavern, a website to review hosting companies. You can check his website if you are looking for arvixe coupon.
linux tips and tricks