【问题标题】:Excluding lines that start with space from egrep printout从 egrep 打印输出中排除以空格开头的行
【发布时间】:2016-02-13 19:54:23
【问题描述】:

我正在尝试编写一个正则表达式 (e)grep 命令,它将打印 txt 文件中的所有行,但忽略那些以空格开头的行(手动缩进文件)。我一直无法弄清楚如何使用^ 行的开头并一起排除^。谢谢!

【问题讨论】:

    标签: regex unix grep


    【解决方案1】:

    使用negated character class 是一个好方法。

    就像[abc] 将匹配abc[^abc] 将匹配任何不是abc 的字符。 ^ 将正则表达式锚定在行首,因此它后面的内容必须匹配字符串的第一个字符。

    $ cat test
    does not start with space
     starts with space
           starts with more spaces
    another good line
    
    $ egrep '^[^ ]' test
    does not start with space
    another good line
    

    如果我们想跳过以空格开头的行,包括制表符,您可以在字符类中使用特殊的[:space:] 括号表达式:

     egrep '^[^[:space:]]' test
    

    如果你不是在行中寻找其他东西,你也可以使用一个反转匹配

     -v, --invert-match
             Selected lines are those not matching any of the specified pat-
             terns.
    

    所以我们可以这样做:

     egrep -v '^[[:space:]]' test
    

    grep 也应该这样做:

     grep -v '^[[:space:]]' test
    

    【讨论】:

      【解决方案2】:

      您可以使用-v 开关跳过匹配的行。

      egrep -v '^ '
      

      man egrep

      【讨论】:

        猜你喜欢
        • 2021-11-28
        • 1970-01-01
        • 2014-06-04
        • 2013-04-10
        • 1970-01-01
        • 1970-01-01
        • 2021-08-04
        • 2012-09-22
        • 1970-01-01
        相关资源
        最近更新 更多