使用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
这个问题或多或少是一个变体
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 列总和。
此外,在另一列中附加百分比,产生以下结果:
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
代码:
$ awk '
BEGIN { FS=OFS="|" }
NR==FNR { s[]+=; next }
{ print [=11=],s[],/(s[]?s[]: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
gawk 方法:
awk -F'|' '{a[]+=; b[NR]=[=10=]}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
这个问题或多或少是一个变体 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 列总和。
此外,在另一列中附加百分比,产生以下结果:
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
代码:
$ awk '
BEGIN { FS=OFS="|" }
NR==FNR { s[]+=; next }
{ print [=11=],s[],/(s[]?s[]: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
gawk 方法:
awk -F'|' '{a[]+=; b[NR]=[=10=]}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