Grep所有行没有#(哈希)或贪婪空间和#(哈希)

时间:2017-02-18 22:19:49

标签: regex linux grep regex-negation regex-greedy

我正在尝试grep不以

开头的conf文件的所有有效行
  • 哈希 (或)
  • 任意数量的空格(0或多个)和散列

下面的正则表达似乎不起作用。

grep ^[^[[:blank:]]*#] /opt/logstash/logstash.conf

grep ^[^[[[:blank:]]*#]] /opt/logstash/logstash.conf

grep ^[^[\s]*#] /opt/logstash/logstash.conf

我试图理解我做错了什么。

FWIW,以下正则表达式有效:

grep -v '^[[:blank:]]*#' /opt/logstash/logstash.conf

1 个答案:

答案 0 :(得分:2)

首先,如果你没有引用你的正则表达式,shell可能会在grep看到它之前扩展它,所以你应该总是引用你的grep regex。

其次,它们不起作用的原因是:[],“括号表达式”匹配它包含的任何元素,或者在使用[^...]时它们的补充。你似乎试图匹配一个否定的字符序列,但这不是[]所做的。

此外,在括号表达式中,字符类不应该是双括号:[^[:blank:]]而不是[^[[:blank:]]]

我不确定是否可以在没有-v和基本或扩展正则表达式的情况下,但是使用可以执行Perl Regular Epxressions的grep(例如GNU grep),你可以使用负面预测:

grep -P '^(?![[:blank:]]*#)' /opt/logstash/logstash.conf

以下是你的正则表达式失败的方式(假设它们被引用):

  • ^[^[[:blank:]]*#] - 匹配以字面[或空格,后跟#]
  • 以外的零个或多个字符开头的任何行
  • ^[^[[[:blank:]]*#]] - 匹配以字面[或空格以外的零个或多个字符开头的任何行(括号表达式中重复的[[与单个{相同} {1}}),然后是[
  • #]] - 匹配以^[^[\s]*#][\以外的零个或多个字符开头的任何行(s在{{\s中并不特殊1}}),然后是[]

如果我们拿这个测试文件:

#]

表达式匹配如下:

  • 您的# comment normal line normal line after spaces # comment after spaces normal line after tab # comment after tab abc#] does not start with blank or [ and has #] [abc#] starts with [ and has #] abc#]] does not start with blank or [ and has #]] abc#]] starts with blank and has #]] sabc#]] starts with s and has #]] \abc#]] starts with \ and has #]] (有效):

    grep -v
  • 我的$ grep -v '^[[:blank:]]*#' infile normal line normal line after spaces normal line after tab abc#] does not start with blank or [ and has #] [abc#] starts with [ and has #] abc#]] does not start with blank or [ and has #]] abc#]] starts with blank and has #]] sabc#]] starts with s and has #]] \abc#]] starts with \ and has #]] (有效):

    grep -P
  • 您的第一次尝试:

    $ grep -P '^(?![[:blank:]]*#)' infile
    normal line
        normal line after spaces
        normal line after tab
    abc#] does not start with blank or [ and has #]
    [abc#] starts with [ and has #]
    abc#]] does not start with blank or [ and has #]]
     abc#]] starts with blank and has #]]
    sabc#]] starts with s and has #]]
    \abc#]] starts with \ and has #]]
    
  • 第二次尝试:

    $ grep '^[^[[:blank:]]*#]' infile
    abc#] does not start with blank or [ and has #]
    abc#]] does not start with blank or [ and has #]]
    sabc#]] starts with s and has #]]
    \abc#]] starts with \ and has #]]
    
  • 第三次尝试:

    $ grep '^[^[[[:blank:]]*#]]' infile
    abc#]] does not start with blank or [ and has #]]
    sabc#]] starts with s and has #]]
    \abc#]] starts with \ and has #]]