How to quickly sum all the numbers in a file on Linux?

LinuxOperating SystemOpen Source

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
raja
Published on 30-Jul-2021 09:08:19
Advertisements