
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
- Related Questions & Answers
- How to Quickly Install WordPress On Ubuntu/Linux Mint
- How to find the most recent file in a directory on Linux?
- How to find all the distinct file extensions in a folder hierarchy (Linux)?
- How to grep and replace a word in a file on Linux?
- How to resume a partially transferred file over ssh on Linux?
- How to suppress a binary file matching results in grep on Linux?
- How to get only the file name using find command on Linux?
- How to encrypt and decrypt a file using gpg command on linux
- How to Recursively Search all Files for Strings on a Linux
- Getting root permissions on a file inside of vi on Linux
- What does opening a file actually do on Linux?
- How to upload a big CSV file in SAP Hybrid mobile app quickly?
- How to list down all the available commands and aliases on Linux?
- How to find all files with names containing a string on Linux?
- How to sort a file in-place in Linux?