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

后端 未结 4 1417
长情又很酷
长情又很酷 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
    
    0 讨论(0)
  • 2020-12-16 06:19

    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.

    0 讨论(0)
  • 2020-12-16 06:20
    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.

    0 讨论(0)
  • 2020-12-16 06:22

    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
    
    0 讨论(0)
提交回复
热议问题