- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 plenty of approaches and solutions that we can consider that involve different commands and keywords. Let’s consider some of these possible solutions one by one.
The most basic approach is to open the file and read the contents and then calculate the sum of all the numbers by making use of the do while loop.
Bash Script
sum=0 while read -r line do (( sum += line )) done < bar echo $sum
In the above example, just replace the keyword bar with the name of your file and then save the file with a .sh extension.
Run the commands shown below to successfully execute the script
Commands
chmod 777 shell.sh ./shell.sh
Output
36
Another approach is to make use of the awk command that Linux provides us with.
Command
awk '{ sum += $1 } END { print sum }' bar
Output
36