如何grep匹配正向超前的行?

问题描述 投票:0回答:2

我正在尝试包含特定模式的行,但仅将字符串返回到该模式且不包括该模式。

例如:

this is a foobar line

我要匹配此行并返回所有内容,直到foobar,因此返回this is a

我尝试使用grep -oE ".*(?=foobar)" test.txt

但是显然,先行与-E标志不兼容。另外,我使用的是Mac,因此没有-P选项。

regex grep regex-lookarounds
2个回答
0
投票

对Perl正则表达式使用-P选项:

grep -oP ".*(?=foobar)" test.txt

0
投票

您可以将foobar留在其中,然后使用revcut将其删除,例如:

cat test.txt | grep -oE ".*foobar" | rev | cut -c7- | rev

有点长,但是有效

© www.soinside.com 2019 - 2024. All rights reserved.