Linux Shell Awk 流程控制語句詳細介紹

在linux awk的 while、do-while和for語句中允許使用break,continue語句來控制流程走向,也允許使用exit這樣的語句來退出。break中斷當前正在執行的循環並跳到循環外執行下一條語句。if 是流程選擇用法。 awk中,流程控制語句,語法結構,與c語言類型。下面是各個語句用法。

條件判斷語句(if)

if(表達式) #if ( Variable in Array )

語句1

else

語句2

格式中”語句1″可以是多個語句,如果你為了方便Unix awk判斷也方便你自已閱讀,你最好將多個語句用{}括起來。Unix awk分枝結構允許嵌套,其格式為:

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,for,do)

1.while語句

格式:

while(表達式)

{語句}

例子:

[chengmo@ localhost nginx]# awk 'BEGIN{

test=100;

total=0;

while(i<=test)

{

total+=i;

i++;

}

print total;

}'

5050

2.for 循環

for循環有兩種格式:

格式1:

for(變量 in 數組)

{語句}

例子:

[chengmo@ localhost nginx]# awk 'BEGIN{

for(k in ENVIRON)

{

print k"="ENVIRON[k];

}

}'

AWKPATH=.:/usr/share/awk

OLDPWD=/home/web97

SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass

SELINUX_LEVEL_REQUESTED=

SELINUX_ROLE_REQUESTED=

LANG=zh_CN.GB2312

。。。。。。

說明:ENVIRON 是awk常量,是子典型數組。

格式2:

for(變量;條件;表達式)

{語句}

例子:

[chengmo@ localhost nginx]# awk 'BEGIN{

total=0;

for(i=0;i<=100;i++)

{

total+=i;

}

print total;

}'

5050

3.do循環

格式:

do

{語句}while(條件)

例子:

[chengmo@ localhost nginx]# awk 'BEGIN{

total=0;

i=0;

do

{

total+=i;

i++;

}while(i<=100)

print total;

}'

5050

以上為awk流程控制語句,從語法上面大家可以看到,與c語言是一樣的。有了這些語句,其實很多shell程序都可以交給awk,而且性能是非常快的。

break當 break 語句用於 while 或 for 語句時,導致退出程序循環。continue當 continue 語句用於 while 或 for 語句時,使程序循環移動到下一個迭代。next能能夠導致讀入下一個輸入行,並返回到腳本的頂部。這可以避免對當前輸入行執行其他的操作過程。exit語句使主輸入循環退出並將控制轉移到END,如果END存在的話。如果沒有定義END規則,或在END中應用exit語句,則終止腳本的執行。

性能比較

[chengmo@ localhost nginx]# 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

[chengmo@ localhost nginx]# 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倍!

Linux Shell Awk 流程控制語句詳細介紹


分享到:


相關文章: