Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to quickly sum all the numbers in a file on Linux?
Consider that we have a file named bar that contains different numbers inside it. The bar file looks something like this −
immukul@192 linux-questions-code % cat bar 11 12 13
We need to get the sum of all the numbers present in the above file. There are several approaches and solutions that we can consider using different commands and techniques. Let's explore these possible solutions one by one.
Bash Script Approach
The most basic approach is to open the file and read the contents, then calculate the sum of all the numbers using a while loop.
sum=0 while read -r line do (( sum += line )) done < bar echo $sum
In the above example, replace the keyword bar with the name of your file and save the script with a .sh extension.
Run the commands shown below to execute the script −
chmod 777 shell.sh ./shell.sh
36
AWK Command Approach
Another efficient approach is to use the awk command that Linux provides. This is a one-liner solution that's particularly useful for quick calculations.
awk '{ sum += $1 } END { print sum }' bar
36
Alternative Methods
Using paste and bc
You can use paste to join numbers with a plus sign and bc to calculate −
paste -sd+ bar | bc
36
Using numsum (if available)
Some systems have the numsum utility for quick numerical summation −
numsum bar
Comparison of Methods
| Method | Speed | Readability | Availability |
|---|---|---|---|
| Bash Script | Slow | High | Always available |
| AWK | Fast | Medium | Usually available |
| paste + bc | Medium | Medium | Usually available |
| numsum | Fast | High | Rarely available |
Conclusion
For quickly summing numbers in a file, the AWK command provides the most efficient one-liner solution. The bash script approach offers better readability and is universally available, while alternative methods like paste+bc provide additional options depending on your system setup.
