【问题标题】:split pcregrep multiline matches拆分 pcregrep 多行匹配
【发布时间】:2018-05-07 14:59:57
【问题描述】:

tl;dr:如何使用 pcregrep 拆分每个多行匹配?

长版本:我的文件中有些行以(小写)字符开头,有些以数字或特殊字符开头。如果我至少有两行以小写字母开头,我希望在我的输出中使用它。但是,我希望每个发现都被分隔/拆分,而不是相互附加。 这是正则表达式:

pcregrep -M "([a-z][^\n]*\n){2,}"

所以如果我给一个这样的文件:

-- Header -- 
info1 
info2 
something 
< not interesting > 
dont need this 
+ new section 
additional 1 
additional 2 

给出的结果是

info1 
info2
something 
additional 1
additional 2 

然而,我想要的是这样的:

info1 
info2 
something 

additional 1
additional 2

这可能和/或我必须开始使用 Python(或类似的)吗?即使建议从这里开始使用其他东西,首先知道它是否可能仍然很高兴。

谢谢!

【问题讨论】:

    标签: regex split pcre multiline pcregrep


    【解决方案1】:

    以下sed 似乎可以解决问题:

    sed -n '/^[a-z]/N;/^[a-z].*\n[a-z]/{p;:l n;/^[a-z]/{p;bl};a\
    
    }'
    

    解释:

    /^[a-z]/{           # if a line starts with a LC letter
      N;                   # consume the next line while conserving the previous one
      /^[a-z].*\n[a-z]/{   # test whether the second line also starts with a LC letter
        p;                   # print the two lines of the buffer
        l: n;                # define a label "l", and reads a new line
        /^[a-z]/{            # if the new line still starts with a LC letter
          p;                   # print it
          bl                   # jump back to label "l"
        }
        a\
                             # append a new line after every group of success 
      }
    }
    

    Sample run

    $ echo '-- Header --
    > info1
    > info2
    > something
    > < not interesting >
    > dont need this
    > + new section
    > additional 1
    > additional 2 ' | sed -n '/^[a-z]/N;/^[a-z].*\n[a-z]/{p;:l n;/^[a-z]/{p;bl};a\
    >
    > }'
    info1
    info2
    something
    
    additional 1
    additional 2
     
    

    【讨论】:

    • 谢谢 Aaron,我以前从未使用过 sed。但是,它似乎对我不起作用,这可能是依赖于终端的问题吗?还是sed版本? ` $ echo '-- 标题 --> info1 > info2 > something > > 不需要这个 > + 新部分 > addit1 > addit2 ' | sed -n '/^[a-z]/N;/^[a-z].*\n[a-z]/{p;:l n;/^[a-z]/{p;bl};a > }' info1 info2 addit1 addit2` 无论如何,很高兴知道 sed 这么强大!
    • @Jyy 很有可能,我只是尝试使用禁用 GNU 扩展的 --posix 标志,但我的 a 语法失败了;我已将答案更新为符合 POSIX 标准。如果您没有错误,则不太可能是问题所在,您能否在ideone 或其他在线解释器上成功重现您的问题?
    • 嗨亚伦,感谢您的回答。我之前在 Macbook 上运行过它,但由于这些问题,我很舒服地切换到 Linux,效果很好:) 谢谢!
    • @Jyy 不客气!请考虑接受答案,因为它解决了您的问题。
    猜你喜欢
    • 1970-01-01
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    相关资源
    最近更新 更多