![AWK で逆正規表現?](https://rvso.com/image/97228/AWK%20%E3%81%A7%E9%80%86%E6%AD%A3%E8%A6%8F%E8%A1%A8%E7%8F%BE%EF%BC%9F.png)
特定の単語を含む行をフィルタリングしようとしています。正規表現はスクリプトへのコマンド ライン入力です。
$0 ~ regex {
//Do something.
}
サンプル入力は次のとおりです。
**String** **number**
domain 1
domain 2
bla 3
したがって、上記の入力から、ユーザーは「domain」という単語を含む行をフィルター処理することができます。
私が試したこと:
regex = "\?\\!domain"
(否定先読み)。
しかし、この正規表現はすべての行をフィルタリングします。「domain」という単語を含む行だけではありません。
答え1
指定された入力ファイルにはinput
次の内容が含まれます。
domain
demesne
次を含む行をフィルタリングするにはdomain
:
$ awk '/domain/ { print }' input
domain
行をフィルタリングするにはない含むdomain
:
$ awk '!/domain/ {print }' input
demesne
フィルタリングには分野行全体ではなく、指定された新しいinput
ファイルに対して次の操作を試すことができます。
example www.example.com
exemplar www.example.net
最初のフィールドが含む example
:
$ awk '$1 !~ /example/ { print }' input
exemplar www.example.net
質問では、$0
最初のフィールドではなく行全体である which を使用しました。
答え2
行をフィルタリングするもう 1 つのより柔軟で強力な方法は、次のとおりです{next}
。
- すべての行を印刷するにはしないでください指定された に一致する場合は
regex
、次のようにします。awk '/regex/ {next} {print}' inputfile
この方法を使用すると、次のように、特定の 2 行の間にあるすべての行をフィルター処理することもできます。
すべての行を印刷するにはない一致する行
regex1
と次の最初の一致する行の間でregex2
、次のようにします。awk '/regex1/,/regex2/ {next} {print}' inputfile
これは、この方法では不可能です
awk '!/regex/'
(私が間違っていなければ)。
たとえば、inputfile
のコンテンツが次のとおりである場合:
hello, here is my confidential information
SECRET INFO BEGIN
xx
x
xxxxx
xxxx
xxxx
xxxxx
xs
sdf
sdfsdfw
wefwe
SECRET INFO END
This is the end of my message
次に、このコマンドは次のawk '/SECRET INFO BEGIN/,/SECRET INFO END/ {next} {print}' inputfile
ように出力します。
hello, here is my confidential information
This is the end of my message
答え3
echo 'hello, here is my confidential information
SECRET INFO BEGIN
xx
x
xxxxx
xxxx
xxxx
xxxxx
xs
sdf
sdfsdfw
wefwe
SECRET INFO END
This is the end of my message' |
mawk 'BEGIN { _^= FS = RS } ! /SECRET INFO/ ? _ : _ * (_=!_)'
gawk 'BEGIN { _^= FS = "SECRET INFO" } _*(NF <= _^_ || _=!_)'
hello, here is my confidential information
This is the end of my message