Grep 查找字符串,但忽略带有字符串的注释掉的项目

Sch*_*mms 3 shell grep scripting text-processing

我正在寻找单词gmail或outlook目录。尽管其中有一些行被注释掉gmail了outlook。grep我该怎么办?

我尝试了很多东西,但我想它会是这样的:

grep "^[^#;]" | egrep -i "gmail|outlook" *.ksh  > a.log
Run Code Online (Sandbox Code Playgroud)

cha*_*aos 5

和grep:

grep -P '^(?=[\s]*+[^#])[^#]*(gmail|outlook)' file
Run Code Online (Sandbox Code Playgroud)
  • -P激活 Perl 兼容的正则表达式。
  • ^(?=...)定义一个不属于模式一部分的捕获组(lookahead;Perl 扩展)。这^意味着该行的开始。
    • 该组内部\s匹配任何空白字符,*+匹配空白 0 次或多次,并且是贪婪的(Perl 扩展)。
    • [^#]匹配任何非#.
  • [^#]*在捕获组之外,我们再次匹配任何非#0 次或多次的字符
  • (gmail|outlook)最后匹配gmail或outlook

我制作了一个包含不同示例的测试文件:

$ cat file
# outlook
blah gmail # this should match
# gmail
  # gmail
        # foo
blah outlook # this should match
  outlook blah # gmail - this should match
foobar # gmail
        bar
        another gmail # this should match
Run Code Online (Sandbox Code Playgroud)

输出是:

blah gmail # this should match
blah outlook # this should match
  outlook blah # gmail - this should match
        another gmail # this should match
Run Code Online (Sandbox Code Playgroud)

当然,您可以对所有*.ksh文件运行此命令:

grep -P '^(?=[\s]*+[^#])[^#]*(gmail|outlook)' *.ksh  > a.log
Run Code Online (Sandbox Code Playgroud)