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

后端 未结 4 1418
长情又很酷
长情又很酷 2020-12-16 06:04

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 o

4条回答
  •  情歌与酒
    2020-12-16 06:13

    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
    

提交回复
热议问题