使用awk基于两个匹配字段的求和列 [英] sum column based on two matching fields using awk

查看:497
本文介绍了使用awk基于两个匹配字段的求和列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于这个简单的任务,我似乎找不到awk解决方案.我可以轻松地基于一个匹配字段($ 1)对列($ 3)进行求和:

I can't seem find an awk solution for this simple task. I can easily sum a column ($3) based on one matching field ($1) with :

awk -F, '{array[$1]+=$3} END { for (i in array) {print i"," array[i]}}' datas.csv

现在,我该如何基于两个字段呢?假设$ 1和$ 2?这是一个示例数据:

Now, how can I do that based on two fields ? Lets say $1 and $2 ? Here is a sample datas :

P1,gram,10  
P1,tree,12  
P1,gram,34  
P2,gram,23  
...

如果第一字段和第二字段匹配,我只需要对第3列求和.

I simply need to sum column 3 if first and second fields match.

感谢您的帮助!

推荐答案

像这样

awk -F, '{array[$1","$2]+=$3} END { for (i in array) {print i"," array[i]}}' datas.csv

我的结果

P1,tree,12
P1,gram,44
P2,gram,23

编辑

由于OP需要逗号保留在输出中,因此我使用@yi_H的逗号修复"编辑了上面的答案.

As the OP needs the commas to remain in the output, I edited the answer above using @yi_H's "comma fix".

这篇关于使用awk基于两个匹配字段的求和列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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