使用awk对一列的值求和,基于另一列的值,将总和和百分比附加到原始数据

使用awk对一列的值求和,基于另一列的值,将总和和百分比附加到原始数据,awk,sum,append,percentage,Awk,Sum,Append,Percentage,这个问题或多或少是一个关于 相同输入: 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 smiths|Login|2|212|0.94 oli

这个问题或多或少是一个关于

相同输入:

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
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
因此,应追加第1列中具有相同模式的所有条目的第3列总和

此外,在另一列中附加百分比,得到以下结果:

smiths|Login|2|212
olivert|Login|10|10
denniss|Payroll|100|100
smiths|Time|200|212
smiths|Logout|10|212
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

下面是一个不舍入百分比但处理零除错误的方法:

向测试数据中添加两条记录:

$ cat >> file
test|test|
test2|test2|0
代码:

输出:

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

下面是一个不舍入百分比但处理零除错误的方法:

向测试数据中添加两条记录:

$ cat >> file
test|test|
test2|test2|0
代码:

输出:

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 -F'|' '{a[$1]+=$3; b[NR]=$0}END{ for(i in b) {split(b[i], data, FS); 
     print b[i] FS a[data[1]] FS sprintf("%0.2f", data[3]/a[data[1]]*100) }}' file
输出:

smiths|Login|2|212|0.94
olivert|Login|10|10|100.00
denniss|Payroll|100|100|100.00
smiths|Time|200|212|94.34
smiths|Logout|10|212|4.72
目瞪口呆接近:

awk -F'|' '{a[$1]+=$3; b[NR]=$0}END{ for(i in b) {split(b[i], data, FS); 
     print b[i] FS a[data[1]] FS sprintf("%0.2f", data[3]/a[data[1]]*100) }}' file
输出:

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