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
他のプログラミング言語と同様に、「break」または「next」を必要に応じて使用します。
または、フラグを使用したい場合:
$ 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
ただし、真の「デフォルト」とまったく同じセマンティクスではないため、そのような使用法は誤解を招く可能性があります。私は通常、すべて大文字の変数名を使用することを推奨しませんが、小文字の「デフォルト」は gawk キーワードと競合するため、スクリプトは将来 gawk に移植できなくなります。