如何在grep中排除“ DEBUG”而不抛出“ BUG”

水果

我想建立一个命令到grep错误关键字的共同列表(例如bug occured!errorexception),但需排除常见的关键字太多(如DEBUG标签),而不抛出匹配行。此命令应足够健壮,以处理各种源/日志。

假设我有这个来源:

$ 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 occuredDEBUG

$ 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

尝试^在grep中使用[UPDATE]错误,^不用于exclude),但它包含DEBUG noop不包含的内容bug(请注意:所有过滤器都应不区分大小写,例如,我要接受BUG occured!和排除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命令或替代命令吗?

芒登

假设使用GNU grep(Linux上的默认设置),则可以使用PCRE模式和否定的lookbehinds

$ 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会匹配bug,除非它是后de(?<!other)stuff会匹配stuff,除非它是后other

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章