8

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
  • 5
    Show example, a few lines of input and desired output. Commented Jan 24, 2014 at 20:41

4 Answers 4

15

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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.

Comments

0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.