[dywang@dywmac zzz]$ vim sdata.txt [dywang@dywmac zzz]$ cat sdata.txt 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 -W help | grep ^Example -A2 Examples: gawk '{ sum += $1 }; END { print sum }' file gawk -F: '{ print $1 }' /etc/passwd
[dywang@dywmac zzz]$ gawk '{sum+=$3}; END {print sum}' sdata.txt 313
[dywang@dywmac zzz]$ gawk '{sum+=$3; count+=1}; END {print sum/count}' sdata.txt 62.6
"\t"
TAB 定位隔開,整齊輸出。
[dywang@dywmac zzz]$ gawk '{ sum += $3; count+=1; \ print count "\t" $2 "\t" $3 "\t" sum "\t" sum/count}' sdata.txt 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
變數名稱 | 代表意義 |
NF | 每一行 ($0) 擁有的欄位總數 |
$NF | 每一行的最後一個欄位內容 |
NR | 目前 awk 所處理的是『第幾行』資料 |
FS | 目前的分隔字元,預設是空白鍵 |
[dywang@dywmac zzz]$ egrep 'NF|NR|FS' ../awkvars.out FNR: number (0) FS: string (" ") NF: number (0) NR: number (0) OFS: string (" ")
[dywang@dywmac zzz]$ gawk '{ sum += $3; \ print NR "\t" $2 "\t" $3 "\t" sum "\t" sum/NR}' sdata.txt 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