16

次の AWK 形式:

/REGEX/ {Action}

Action現在の行が一致する場合に実行されREGEXます。

elseif-then-else を明示的に使用せずに、現在の行が正規表現と一致しない場合に実行される句を追加する方法はありますか?

/REGEX/ {Action-if-matches} {Action-if-does-not-match}
4

3 に答える 3

17

それほど短くない:

/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 }
于 2013-01-23T11:36:53.383 に答える
14

もありますnext

/REGEX/ {
    Action
    next # skip to the next line
}
{ will only get here if the current line does *not* match /REGEX/ }
于 2013-01-23T14:30:47.073 に答える
1

あなたは「トリック」をすることができます。ご存じのとおり、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 !!
于 2013-01-23T12:45:15.857 に答える