GNU AWK有switch語句:
$ cat tst1.awk
{
switch($0)
{
case /a/:
print "found a"
break
case /c/:
print "found c"
break
default:
print "hit the default"
break
}
}
$ cat file
a
b
c
d
$ gawk -f tst1.awk file
found a
hit the default
found c
hit the default
或者與任何AWK:
$ cat tst2.awk
/a/ {
print "found a"
next
}
/c/ {
print "found c"
next
}
{
print "hit the default"
}
$ awk -f tst2.awk file
found a
hit the default
found c
hit the default
使用 「破發」 或 「下一個」 是/當你想,就像在其他編程語言。
或者,如果你喜歡使用標誌:
$ cat tst3.awk
{ DEFAULT = 1 }
/a/ {
print "found a"
DEFAULT = 0
}
/c/ {
print "found c"
DEFAULT = 0
}
DEFAULT {
print "hit the default"
}
$ gawk -f tst3.awk file
found a
hit the default
found c
hit the default
這不是exaclty相同的語義作爲一個真正的「默認」,但這樣它的用法一樣,可能會產生誤導。我通常不會主張使用全大寫變量名,但小寫「default」會與gawk關鍵字衝突,因此腳本將來不會移植到gawk。
除了提示使用'next'的錯誤之外,這與我的回答有何不同呢? –
ooops - 你的權利 - 對不起。 – tue