次の AWK 形式:
/REGEX/ {Action}
Action
現在の行が一致する場合に実行されREGEX
ます。
else
if-then-else を明示的に使用せずに、現在の行が正規表現と一致しない場合に実行される句を追加する方法はありますか?
/REGEX/ {Action-if-matches} {Action-if-does-not-match}
次の AWK 形式:
/REGEX/ {Action}
Action
現在の行が一致する場合に実行されREGEX
ます。
else
if-then-else を明示的に使用せずに、現在の行が正規表現と一致しない場合に実行される句を追加する方法はありますか?
/REGEX/ {Action-if-matches} {Action-if-does-not-match}
それほど短くない:
/REGEX/ {Action-if-matches}
! /REGEX/ {Action-if-does-not-match}
ただし、(g)awk は三項演算子もサポートしています。
{ /REGEX/ ? matching=1 : matching = 0 ; if ( matching ==1 ) { matching_action } else { notmatching_action } }
更新:
偉大な Glenn Jackman によると、次のように試合に変数を割り当てることができます。
m = /REGEX/ { matching-action } !m { NOT-matching-action }
もありますnext
:
/REGEX/ {
Action
next # skip to the next line
}
{ will only get here if the current line does *not* match /REGEX/ }
あなたは「トリック」をすることができます。ご存じのとおり、AWK は入力を各正規表現に順番に一致させて、そのブロックを実行しようとします。
このコードは、$1 が "1" の場合は 2 番目のブロックを実行し、それ以外の場合は 3 番目のブロックを実行します。
awk '{used = 0} $1 == 1 {print $1" is 1 !!"; used = 1;} used == 0 {print $1" is not 1 !!";}'
入力が次の場合:
1
2
それは印刷します:
1 is 1 !!
2 is not 1 !!