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(或类似的)?即使建议从这里使用其他东西,但是首先要知道它是否可能仍然是很好的。
谢谢!
答案 0 :(得分: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
}
}
$ 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