GROUP BY/SUM from shell

前端 未结 6 1518
既然无缘
既然无缘 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:15

    Edit: The modern (GNU/Linux) solution, as mentioned in comments years ago ;-) .

    awk '{
        arr[$1]+=$2
       }
       END {
         for (key in arr) printf("%s\t%s\n", key, arr[key])
       }' file \
       | sort -k1,1
    

    The originally posted solution, based on old Unix sort options:

    awk '{
        arr[$1]+=$2
       }
       END {
         for (key in arr) printf("%s\t%s\n", key, arr[key])
       }' file \
       | sort +0n -1
    

    I hope this helps.

提交回复
热议问题