2017-04-27 18 views
1

這個問題是更多或更少上的變體 https://unix.stackexchange.com/questions/242946/using-awk-to-sum-the-values-of-a-column-based-on-the-values-of-another-column使用AWK總結列的值的基礎上,另一列的值,總和和百分比附加到原始數據

相同的輸入:

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列的總和的所有條目與colu相同的圖案應該附加mn 1。

此外,追加另一列用百分比,得到以下結果:

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 

回答

3

這裏是一個不圓的百分比,而是由零個錯誤處理師:

添加到測試數據幾個記錄:

$ 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 
+1

偉大的作品,謝謝! – Markus

1

呆子方法:

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 
+0

也很好,謝謝! – Markus