awk腳本linux
awk腳本一般由如下3部分構成: BEGIN{ 這裏面放的是執行前的語句 } END {這裏面放的是處理完全部的行後要執行的語句 } {這裏面放的是處理每一行時要執行的語句}
假若有如下表:get
$ cat score.txt Marry 2143 78 84 77 Jack 2321 66 78 45 Tom 2122 48 77 71 Mike 2537 87 97 95 Bob 2415 40 57 62
統計全部人有總錢數,及平均狀況的awk腳本:awk
#!/bin/awk -f #運行前 BEGIN { math = 0 english = 0 computer = 0 printf "NAME NO. MATH ENGLISH COMPUTER TOTAL\n" printf "---------------------------------------------\n" } #運行中 { math+=$3 english+=$4 computer+=$5 printf "%-6s %-6s %4d %8d %8d %8d\n", $1, $2, $3,$4,$5, $3+$4+$5 } #運行後 END { printf "---------------------------------------------\n" printf " TOTAL:%10d %8d %8d \n", math, english, computer printf "AVERAGE:%10.2f %8.2f %8.2f\n", math/NR, english/NR, computer/NR }
輸出結果:統計
NAME NO. MATH ENGLISH COMPUTER TOTAL -------------------------------------------------- Marry 2143 78 84 77 239 Jack 2321 66 78 45 189 Tom 2122 48 77 71 196 Mike 2537 87 97 95 279 Bob 2415 40 57 62 159 -------------------------------------------------- TOTAL: 319 393 350 AVERAGE: 63.80 78.60 70.00