使用awk根据单词求和 [英] Summing up numbers based on the word using awk

查看:85
本文介绍了使用awk根据单词求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有多个句子行,它们在这些输出之一中.

There are multiple sentences lines, and they are in one of these outputs.

[%d][%d] msg_sent = %result

[%d][%d] msg_sent_node number = %result2

其中%d,$ result和$ result2是数字.

where %d, $result, and $result2 are numbers.

这些行是随机排序的.

These lines are randomly ordered.

我想对%result和%result2中的所有数字求和,因此它将在末尾打印2个数字(第一个是%result中所有数字的总和,第二个是%result中所有数字的总和. %result2格式.)

I want to sum up all the numbers that are in %result, and %result2 so it will print 2 numbers at the end (First one is sum of all numbers in %result, and second one is sum of all numbers in %result2 format.)

例如,如果文件由以下4行组成

For example, if file consist of below 4 lines

[1][1] msg_sent = 5000
[1][2] msg_sent = 6000
[1][2] msg_sent_node number = 100
[1][1] msg_sent_node number = 200

我希望2个输出数字分别为11000和300.

I want 2 output numbers to be 11000, and 300.

如何使用awk做到这一点?

How can I do that using awk?

推荐答案

awk '/msg_sent_node number/ { node_total += $5  } /msg_sent / { sent_total = sent_total + $4} END { print sent_total " " node_total }'

如果这样写的话,可能会更容易理解:

which is probably easier to understand if written like so:

/msg_sent_node number/ { node_total += $5 } 
/msg_sent / { sent_total += $4} 
END { print sent_total " " node_total }

这篇关于使用awk根据单词求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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