代码之家  ›  专栏  ›  技术社区  ›  Andy Fleming

我如何用grep匹配不以序列开头的字符串

  •  1
  • Andy Fleming  · 技术社区  · 12 年前

    我正在运行以下命令:

    grep -REin "Example::" .

    我正在努力过滤我的结果。我想搭配任何东西 Example:: 除非它以 return 就像在案例中一样 return Example:: .

    匹配

    if (Example::test())
    

    不匹配

    if (something()) return Example::another()
    
    2 回复  |  直到 12 年前
        1
  •  4
  •   hwnd    12 年前

    您可以使用 -v (反转匹配)选项。

    grep -REin 'Example::' . | grep -vi 'return Example::'
    

    或使用选项 -P 这将模式澄清为Perl正则表达式。

    grep -RPin '(?<!return )Example::' .
    

    这使用 Negative Lookbehind 断言前面的不是单词 回来 .

    (?<!         # look behind to see if there is not:
      return     #   'return '
    )            # end of look-behind
    Example::    # 'Example::'
    
        2
  •  1
  •   Jotne    12 年前

    你可以使用 awk 要解决此问题:

    awk '/Example/ && !/return Example/' file
    if (Example::test())