用括号无法理解正则表达式

时间:2017-09-20 18:10:53

标签: regex text grep

如果文件只包含带有“.get”扩展名的行,那么如何通过regexp为helloworld(...)的文件进行grep?

a(text)

b(text)

helloworld(
text.get
text.get
text.get
text.get
)
c(text)

然后,这样的例子:

a(text)

b(text)

helloworld(
text.pass
text.pass
text.pass
text.pass
)
c(text)

不应该找到

我尝试了regexp [a-z_]+\.get,但它有助于查找带扩展名的文件,但我不知道如何用helloworld(打包并以)结尾

2 个答案:

答案 0 :(得分:2)

如果您有gnu grep,那么您可以使用-z选项将文件视为行序列,并使用此命令列出匹配的块:

grep -zoP 'helloworld\s*\(\s*(\w+\.get\b\s*)+\)\s*' file

要列出目录中的所有匹配文件,请使用:

grep -zPl 'helloworld\s*\(\s*(\w+\.get\b\s*)+\)\s*' file*

答案 1 :(得分:1)

AKAIK grep一次一行。

这个perl单行做你想做的事:

perl -0777 -ne 'print $& if /helloworld\(\R(?:[a-z_]+\.get\R)+\)/' file

第一个文件的结果:

helloworld(
text.get
text.get
text.get
text.get
)

第二个文件的结果:

NOTHING