「BUG」を生成せずにgrepから「DEBUG」を除外する方法

「BUG」を生成せずにgrepから「DEBUG」を除外する方法

一般的なエラーキーワード(たとえば、、、)のリストをgrepするコマンドを作成しようとしていますbug occured!が、一致する行を破棄せずに通常のキーワード(タグなど)も除外する必要があります。コマンドは、さまざまなソース/ログを処​​理できるほど強力でなければなりません。errorexceptionDEBUG

次のソースがあるとしましょう。

$ cat dummy.log 
12345   DEBUG   debug.log abc
!DEBUG
!bug
!debug
DEBUG noop
12345 DEBUG bug occured
please report BUG to me
the filename is critical_bug.log
bug should be fix.
noop
throws error
a stuff
b otherstuff
c otherstuff stuff

bugこのコマンドは、以下を12345 DEBUG bug occured含む行を除外するため、機能しませんDEBUG

$ cat -v dummy.log | nl | grep -Ei 'bug|stuff|error' | grep -Evi 'DEBUG|otherstuff'
 3  !bug
 7  please report BUG to me
 8  the filename is critical_bug.log
 9  bug should be fix.
11  throws error
12  a stuff

パイプ交換手順も上記と同じです。

$ cat -v dummy.log | nl | grep -Evi 'DEBUG|otherstuff' | grep -Ei 'bug|stuff|error'
 3  !bug
 7  please report BUG to me
 8  the filename is critical_bug.log
 9  bug should be fix.
11  throws error
12  a stuff

^【書き直す】偽、^除外には使用されませんDEBUG noop)、しかしそうでないものも含めますbug(注:すべてのフィルタは大文字と小文字を区別する必要があります。例:I want to accept BUG occured!and extra debug.log)。

 $ cat -v dummy.log | nl | grep -Ei 'bug|stuff|error|^DEBUG|^otherstuff'
 1  12345   DEBUG   debug.log abc
 2  !DEBUG
 3  !bug
 4  !debug
 5  DEBUG noop
 6  12345 DEBUG bug occured
 7  please report BUG to me
 8  the filename is critical_bug.log
 9  bug should be fix.
11  throws error
12  a stuff
13  b otherstuff
14  c otherstuff stuff

debug以下を使用している場合にのみ除外をカスタマイズできます-w(例:包含失敗)。the filename is critical_bug.log

$ grep -wnEi 'bug|stuff|error' dummy.log 
3:!bug
6:12345 DEBUG bug occured
7:please report BUG to me
9:bug should be fix.
11:throws error
12:a stuff
14:c otherstuff stuff

私の予想出力(注:一致する色と元の行番号を維持する必要があります):

$ grep -wnEi 'bug|stuff|error' dummy.log 
3:!bug
6:12345 DEBUG bug occured
7:please report BUG to me
8:the filename is critical_bug.log
9:bug should be fix.
11:throws error
12:a stuff
14:c otherstuff stuff

grepこのコマンドや代替手段を使用できますか?

ベストアンサー1

GNU grep(Linuxのデフォルト)を想定すると、PCREモードを使用できます。否定的なレビュー:

$ grep -niP '(?<!de)bug|(?<!other)stuff|error' dummy.log 
3:!bug
6:12345 DEBUG bug occured
7:please report BUG to me
8:the filename is critical_bug.log
9:bug should be fix.
11:throws error
12:a stuff
14:c otherstuff stuff

使用されるオプションは次のとおりです。

-n, --line-number
    Prefix each line of output with the 1-based line number within 
        its input file.

-i, --ignore-case
    Ignore case distinctions in patterns and input data, so that
    characters that differ only in case match each other.

-P, --perl-regexp
    Interpret  PATTERNS  as  Perl-compatible regular expressions (PCREs).
    This option is experimental when combined with the  -z  (--null-data)
    option, and grep -P may warn of unimplemented features.

魔法は振り返ってみると起こります。一般的な形式は(?!<foo)bar「一致しますbarが」を意味します。ただfoo前に「.」がない場合は後に表示されない限り一致し(?<!de)bug、後に表示されない場合は一致します。bugde(?<!other)stuffstuffother

おすすめ記事