【问题标题】:first occurance for pattern across multiple lines using pcregrep使用 pcregrep 跨多行模式的首次出现
【发布时间】:2021-06-04 07:12:41
【问题描述】:

参考下面的问题,似乎 pcregrep 不会将结果缩小到第一次出现,而是尽可能地扩展。因此,如果例如内容是:

blah blah..
blah blah..
blah abc blah
blah blah..
blah blah..
blah blah..
blah efg1 blah blah
blah blah..
blah blah..
blah efg2 blah blah
blah blah..
blah blah..

输出上升到 efg2,而我希望只到 efg1,后者是第一次出现。有什么想法可以实现吗?

How to find patterns across multiple lines using grep?

【问题讨论】:

  • 请尝试pcregrep -M 'abc.*(\n|.)*?efg' test.txt 进行非贪婪匹配。
  • 成功了!非常感谢!

标签: regex grep pcregrep


【解决方案1】:

使用

pcregrep -M  '(?s)abc.*?efg' test.txt

regex proof

解释

--------------------------------------------------------------------------------
  (?s)                     set flags for this block (with . matching
                           \n) (case-sensitive) (with ^ and $
                           matching normally) (matching whitespace
                           and # normally)
--------------------------------------------------------------------------------
  abc                      'abc'
--------------------------------------------------------------------------------
  .*?                      any character (0 or more times (matching
                           the least amount possible))
--------------------------------------------------------------------------------
  efg                      'efg'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-25
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    • 2014-12-04
    相关资源
    最近更新 更多