Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I calculate the sum of a specific column using bash?

Tags:

bash

sum

I want to calculate the sum of a specific column using bash without using the print that specific column (I want to keep all the output columns of my pipeline and only sum one of them!)

like image 413
Nikleotide Avatar asked Jan 24 '14 20:01

Nikleotide


People also ask

How do you get the sum of a column in Linux?

“UtilityBills. txt” represents the name of the text file from which we have to read the data. Then we have the “awk” keyword followed by the “sum” expression that will actually calculate the sum from the second column of our dataset, and then the “print” command will be used to display the results on the terminal.


1 Answers

If you wanted to sum over, say, the second column, but print all columns in some pipeline:

cat data | awk '{sum+=$2 ; print $0} END{print "sum=",sum}'

If the file data looks like:

1 2 3
4 5 6
7 8 9

Then the output would be:

1 2 3
4 5 6
7 8 9
sum= 15
like image 173
John1024 Avatar answered Sep 21 '22 16:09

John1024