[英]Sum of tagged lines perl/shellscript
I have input that looks like 我输入的内容看起来像
5 X
8 Y
3 Z
9 X
I want output that sums the numerical values for each 'tag'; 我想要输出求和每个“标签”的数值的总和; eg
例如
14 X
8 Y
3 Z
Wondering if there is a slick one liner I can use (along the lines of the ones for summing a list of integers using awk). 我想知道是否可以使用一个光滑的衬里(沿着那些衬里使用awk对整数列表求和)。
Something like this should do the trick: 这样的事情应该可以解决问题:
perl -ne '$table{$2} += $1 if /(\d+)\s+(.+)/; END {print "$table{$_} $_\n" for keys %table}'
or to use auto-splitting: 或使用自动拆分:
perl -ane '$table{$F[1] or next} += $F[0]; END {print "$table{$_} $_\n" for keys %table}'
我可以做到的很圆滑:
perl -alne 'END{print"$X{$_} $_"for sort{$X{$b}<=>$X{$a}}keys%X}$X{$F[1]}+=$F[0]'
试图使它尽可能少被混淆:)按“标签”对输出进行排序。
perl -alne '$counts{$F[1]} += $F[0]; END { print "$counts{$_} $_" for sort(keys %counts) }'
Output in random order 随机输出
perl -alne'$t{$F[1]}+=$F[0]}{print"$t{$_} $_"for keys%t'
alphabetically sorted by tag 按标签字母顺序排序
perl -alne'$t{$F[1]}+=$F[0]}{print"$t{$_} $_"for sort keys%t'
sorted by value 按价值排序
perl -alne'$t{$F[1]}+=$F[0]}{print"$t{$_} $_"for sort{$t{$b}<=>$t{$a}}keys%t'
gawk "{count[$2]+=$1}END{for(i in count)print count[i],i}" 1.t
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.