在bash中对键进行排序和求和

car*_*ray 6 bash awk

我有一个字符串列表(stdin),如下:

1 pineapples
28 apples
16 oranges
8 apples
2 apples
2 oranges
56 pineapples
Run Code Online (Sandbox Code Playgroud)

是否有一种原生的方式(比如sort&uniq -c),我可以合并并将它们总结如下:

38 apples
18 oranges
57 pineapples
Run Code Online (Sandbox Code Playgroud)

喜欢sort |uniq -c做,但不仅仅是出现次数?

Pav*_*vel 13

试试这个:

awk '{a[$2] += $1} END{for (i in a) print a[i], i}' < in.txt
Run Code Online (Sandbox Code Playgroud)

输出

38 apples
57 pineapples
18 oranges
Run Code Online (Sandbox Code Playgroud)

  • 当awk是适合这项工作的工具时,它确实是适合这项工作的工具. (3认同)