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 that specific column (I want to save all the output columns of my pipeline and only sum one of them!)

+4
source share
4 answers

If you want to list, say, the second column, but print all the columns in some kind of pipeline:

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

If the file data is as follows:

1 2 3
4 5 6
7 8 9

Then the output will be:

1 2 3
4 5 6
7 8 9
sum= 15
+7
source

Do you want to summarize one column at a time, step by step?

Should be bashor you can 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
+1
source

, @John1024, ol 'cut paste, :

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

The trick here is to say pasteinsert +as a separator, and then do the bash arithmetic using $(( ))in the resulting expression.

Note. I am just catentering the input for illustrative purposes - it can be transferred from another source or data file transferred directly to cut.

0
source
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 1st column 15.

0
source

Source: https://habr.com/ru/post/1523612/


All Articles