[dywang@dywmac zzz]$ vim sdata.txt [dywang@dywmac zzz]$ cat sdata.txt no. name score1 score2 grade 11 dywang 81 12 A 152 linda 90 58 C 33 peter 72 95 C 4 rita 65 34 E 58 cora 5 85 D
[dywang@dywmac zzz]$ gawk '{ sum += $3; \ print NR "\t" $2 "\t" $3 "\t" sum "\t" sum/NR}' sdata.txt 1 name score1 0 0 2 dywang 81 81 40.5 3 linda 90 171 57 4 peter 72 243 60.75 5 rita 65 308 61.6 6 cora 5 313 52.1667
{ }
內動作加 if 條件,將一列個別處理。
[dywang@dywmac zzz]$ gawk '{if(NR==1) print "count\tname\tscore1\tsum\tavg."} \ {sum += $3; if(NR>=2) print NR-1 "\t" $2 "\t" $3 "\t" sum "\t" sum/(NR-1)}' sdata.txt count name score1 sum avg. 1 dywang 81 81 81 2 linda 90 171 85.5 3 peter 72 243 81 4 rita 65 308 77 5 cora 5 313 62.6
[dywang@dywmac zzz]$ gawk '{if(NR==1) print "count\tname\tscore1\tscore2\tavg."} \ {sum = $3+$4; if(NR>=2) print NR-1 "\t" $2 "\t" $3 "\t" $4 "\t" sum/2}' sdata.txt count name score1 score2 avg. 1 dywang 81 12 46.5 2 linda 90 58 74 3 peter 72 95 83.5 4 rita 65 34 49.5 5 cora 5 85 45
NR==1, NR>=2
的判斷放在大括號 {}
動作外,則表示「條件」,不用再用 if
處理。
[dywang@dywmac zzz]$ gawk 'NR==1 {print "count\tname\tscore1\tscore2\tavg."} \ NR>=2 {sum = $3+$4; print NR-1 "\t" $2 "\t" $3 "\t" $4 "\t" sum/2}' sdata.txt count name score1 score2 avg. 1 dywang 81 12 46.5 2 linda 90 58 74 3 peter 72 95 83.5 4 rita 65 34 49.5 5 cora 5 85 45