使用awk对一列的值求和,基于另一列的值,将总和和百分比附加到原始数据 [英] Using awk to sum the values of a column, based on the values of another column, append the sum and percentage to original data

查看:18
本文介绍了使用awk对一列的值求和,基于另一列的值,将总和和百分比附加到原始数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题或多或少是一个变体https://unix.stackexchange.com/questions/242946/using-awk-to-sum-the-values-of-a-column-based-on-the-values-of-another-column

This question is more or less a variant on https://unix.stackexchange.com/questions/242946/using-awk-to-sum-the-values-of-a-column-based-on-the-values-of-another-column

相同的输入:

smiths|Login|2
olivert|Login|10
denniss|Payroll|100
smiths|Time|200
smiths|Logout|10

我希望得到以下结果:

smiths|Login|2|212
olivert|Login|10|10
denniss|Payroll|100|100
smiths|Time|200|212
smiths|Logout|10|212

因此,应附加第 1 列中具有相同模式的所有条目的第 3 列总和.

Hence, the sum of column 3 for all entries with the same pattern in column 1 should be appended.

此外,附加另一列与百分比,产生以下结果:

In addition, append another column with the percentage, yielding the following result:

smiths|Login|2|212|0.94
olivert|Login|10|10|100
denniss|Payroll|100|100|100
smiths|Time|200|212|94.34
smiths|Logout|10|212|4.72

推荐答案

这里有一个不舍入百分比但处理除以零错误的方案:

Here's one that doesn't round the percentages but handles division by zero errors:

向测试数据添加几条记录:

Adding to test data a couple of records:

$ cat >> file
test|test|
test2|test2|0

代码:

$ awk '
BEGIN { FS=OFS="|" }
NR==FNR { s[$1]+=$3; next }
{ print $0,s[$1],$3/(s[$1]?s[$1]:1)*100 }
' file file

输出:

smiths|Login|2|212|0.943396
olivert|Login|10|10|100
denniss|Payroll|100|100|100
smiths|Time|200|212|94.3396
smiths|Logout|10|212|4.71698
test|test||0|0
test2|test2|0|0|0

这篇关于使用awk对一列的值求和,基于另一列的值,将总和和百分比附加到原始数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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