awk或sed在行中求和相似的值 [英] awk or sed sum similar value in rows

查看:75
本文介绍了awk或sed在行中求和相似的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,其值如下:

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...

这篇关于awk或sed在行中求和相似的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆