awk 的 while、do-while、for 迴圈支援 break、continue 控制流向,exit 退出。if 為條件選擇。語法結構與 C 語言相似。
if (表達式)
陳述句1
else
陳述句2
多陳述句建議用 {} 包裹。支援巢狀:
if (表達式) {
陳述句1
} else if (表達式) {
陳述句2
} else {
陳述句3
}
[chengmo@localhost nginx]# awk 'BEGIN{
test=100;
if(test>90) { print "very good"; }
else if(test>60) { print "good"; }
else { print "no pass"; }
}'
very good
每句可用分號結尾。
while (表達式) { 陳述句 }
awk 'BEGIN{
test=100; total=0; i=1;
while(i<=test) { total+=i; i++; }
print total;
}'
5050
格式一:遍歷陣列
for (變數 in 陣列) { 陳述句 }
awk 'BEGIN{
for(k in ENVIRON) { print k"="ENVIRON[k]; }
}'
格式二:C 風格
for (變數; 條件; 表達式) { 陳述句 }
awk 'BEGIN{
total=0;
for(i=0;i<=100;i++) { total+=i; }
print total;
}'
5050
do { 陳述句 } while (條件)
awk 'BEGIN{
total=0; i=0;
do { total+=i; i++; } while(i<=100)
print total;
}'
5050
break:跳出當前 while/for 迴圈continue:進入下一次迭代next:讀取下一行輸入,回到腳本頂部exit:退出主輸入迴圈,轉入 END 區塊(若存在);若在 END 中或無 END 則終止腳本# awk 版
$ time (awk 'BEGIN{ total=0; for(i=0;i<=10000;i++){total+=i;} print total; }')
50005000
real 0m0.003s
user 0m0.003s
sys 0m0.000s
# Shell 版
$ time (total=0; for i in $(seq 10000); do total=$(($total+i)); done; echo $total)
50005000
real 0m0.141s
user 0m0.125s
sys 0m0.008s
結論:相同功能下,awk 效能約為 Shell 迴圈的 50 倍。許多 Shell 程式可移植至 awk 獲得極大效能提升。