如何基于Awk中另一列中的值求和列中的值 [英] How can I sum values in column based on the value in another column in Awk
问题描述
输入:
TT,SS,ECID,CDID,ODID,Symbol,Side,LastQty,LastPx,CumQty,AvgPx,
"20191008-13:32:52","RO","0284","378MT","r7ot","SPD","1","100","290.67","400","290.67",
"20191008-13:33:13","RO","02DJ","378MT","r7o","SPD","1","100","290.68","2248","290.655",
"20191008-13:33:26","RO","FATS","378MTA","r7ot","PDF","1","100","290.92","2751","290.608",
输出应为:
SPD 200
PDF 100
试图用它来做,但不起作用
Tried doing it using but doesn't work
$ awk '{a[$3]+=$4}END{for(i in a) print i,a[i]}' file
推荐答案
然后我添加了以下代码的示例.
Since OP has old awk
where FPAT
is not there so as per samples I added following code then.
awk -F, '{gsub(/\r/,"")} FNR>1{gsub(/"/,"",$8);gsub(/"/,"",$6);a[$6]+=$8} END{for(i in a){print i,a[i] | "sort -k1"}}' Input_file
:由于OP完全更改了Input_file,因此现在添加此解决方案.用GNU awk
编写并测试.
Since OP changed Input_file completely so adding this solution now. Written and tested with GNU awk
.
awk -v FPAT='[^,]*|"[^"]+"' '
gsub(/\r/,"")
FNR>1{
gsub(/"/,"",$8)
gsub(/"/,"",$6)
a[$6]+=$8
}
END{
for(i in a){
print i,a[i]
}
}
' Input_file
或按字母顺序对输出进行排序,请尝试以下操作.
OR to sort output in alphabetic order try following.
awk -v FPAT='[^,]*|"[^"]+"' '{gsub(/\r/,"")} FNR>1{gsub(/"/,"",$8);gsub(/"/,"",$6);a[$6]+=$8} END{for(i in a){print i,a[i] | "sort -k1"}}' Input_file
您亲近了,您的方法遇到的问题是您尚未在代码中将字段分隔符设置为,
,但是Input_file的分隔符设置为,
,因此根本没有$3
,因此无法正常工作.您能不能试一下.
You were close, problem with your approach is you haven't set field separator as ,
in your code but your Input_file has separator as ,
so it is not having $3
at all and hence not working. Could you please try following.
awk -F"[[:space:]]*,[[:space:]]*" 'FNR>1{a[$3]+=$4} END{for(i in a){print i,a[i]}}' Input_file
PS:感谢oguz ismail通知了字段分隔符集.
PS: Thanks to oguz ismail for letting know about field separator set.
这篇关于如何基于Awk中另一列中的值求和列中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!