GROUP BY/SUM from shell

前端 未结 6 1510
既然无缘
既然无缘 2020-11-28 11:52

I have a large file containing data like this:

a 23
b 8
a 22
b 1

I want to be able to get this:

a 45
b 9

6条回答
  •  时光取名叫无心
    2020-11-28 12:23

    One way using perl:

    perl -ane '
        next unless @F == 2; 
        $h{ $F[0] } += $F[1]; 
        END { 
            printf qq[%s %d\n], $_, $h{ $_ } for sort keys %h;
        }
    ' infile
    

    Content of infile:

    a 23
    b 8
    a 22
    b 1
    

    Output:

    a 45
    b 9
    

提交回复
热议问题