Nikleotide
Nikleotide

Reputation: 172

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

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!)

Upvotes: 8

Views: 22362

Answers (4)

krishna murti
krishna murti

Reputation: 1061

awk '{sum+=$1;} END { print "Total of 1st Column:" sum }1' abc.t6RrMm 

Given a file like:

12 12 12 
1  1  1
2  2  1
0  1  2

Total of 1st Column is 15.

Upvotes: 0

Digital Trauma
Digital Trauma

Reputation: 15996

Assuming the same input data as @John1024, you can use good ol' cut and paste and some arithmetic:

$ cat data | echo $(( $( cut -d' ' -f2 | paste -s -d+ - ) ))
15
$ 

The trick here is to tell paste to insert + as a delimiter, then perform bash arithmetic using $(( )) on the resulting expression.

Note I am just cating the input data for illustrative purposes - it could be piped from another source, or the data file passed directly to cut as well.

Upvotes: 1

John1024
John1024

Reputation: 113844

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

Upvotes: 15

grebneke
grebneke

Reputation: 4494

Do you want to continuously sum one column, step by step?

Does is have to be bash or can you use awk:

# file 'fields.txt':
1 foo
2 bar
10 baz
8 boz

# Step by step sum the first column:
awk '{s+=$1; print s, $2}' < fields.txt

# Output:
1 foo
3 bar
13 baz
21 boz

Upvotes: 1

Related Questions