我有一个文件,其值如下:
I have a file with values such as:
(X1 55) (X2 99) (X3 29) (X1 3) (X3 10) (X1 21) (X3 11) (X1 9)是否可以通过每行中的Xn名称添加值:
Is there a way to add the values by the Xn names in each row:
(X1 58) (X2 99) (X3 39) (X1 30) (X3 11)我不确定awk,sed或...是哪种最佳使用方式?我尝试过:
I'm not sure which is best to use, awk, sed or...? I tried this:
awk '{for (i=t=0;i<NF;) t+=$++i; $0=t}1' file 196 41它显然将所有值加在一起,所以也许有点复杂.
It obviously sums all values together, so maybe it's a bit more complex.
推荐答案$ awk '{ for (i=1;i<NF;i+=2) { sum[$i]+=$(i+1) } ofs = "" for (key in sum) { printf "%s%s %d)", ofs, key, sum[key] delete sum[key] ofs = OFS } print "" }' file (X2 99) (X3 39) (X1 58) (X3 11) (X1 30)
如果您关心字段的顺序,可以通过多种方法来保持原始顺序...
If you care about the order of the fields, there's various ways to keep the original order...