How Can I calculate the sum of a specific column u

2019-01-24 13:33发布

问题:

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

回答1:

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


回答2:

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


回答3:

Assuming the same input data as @John1024, you can use good ol' cut and paste and some bash 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.



回答4:

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.



标签: bash sum