【shell】awk 分组

时间:2022-11-11 11:58:17


直接用数组即可。

 

a.txt文件:

Tom baidu 8000
Jerry alibaba 9000
Jack tencent 8500
Nika baidu 7500

1.分组求和,排序

awk '{count[$2] += $3}END{for(i in count) print i, count[i]}' a.txt | sort -nrk 2
baidu 15500
alibaba 9000
tencent 8500

2.分组求平均,排序

awk '{count[$2] += $3;c[$2] += 1}END{for(i in count) print i, count[i]/c[i]}' a.txt | sort -nrk 2
alibaba 9000
tencent 8500
baidu 7750

3.分组最大值,排序

awk '{if(count[$2] < $3)count[$2] = $3}END{for(i in count) print i, count[i]}' a.txt | sort -nrk 2
alibaba 9000
tencent 8500
baidu 8000