使用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
本文介绍了使用awk对另一列的值求和,并将其和百分比添加到原始数据的基础上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个问题或多或少是
上的一个变体> https://unix.stackexchange.com/questions/242946/using-awk-to-sum-the-values-of-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
因此,第3列的总和为
此外,在另一列中添加百分比,将产生以下结果:
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屋!
查看全文