最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

awk或sed在行中求和相似的值

SEO心得admin103浏览0评论
本文介绍了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...

发布评论

评论列表(0)

  1. 暂无评论