Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux awk 流程控制語句完整指南:if、while、for、do 與效能比較

編輯:Linux 教學

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

每句可用分號結尾。

二、迴圈語句

1. while 迴圈

while (表達式) { 陳述句 }

範例:計算 1+...+100

awk 'BEGIN{
test=100; total=0; i=1;
while(i<=test) { total+=i; i++; }
print total;
}'
5050

2. for 迴圈(兩種格式)

格式一:遍歷陣列

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

3. do-while 迴圈

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 vs Shell 迴圈

# 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 獲得極大效能提升。

Copyright © Windows教程網 All Rights Reserved