sed 中的lookbehind 工作吗?
我使用 grep
创建了一个测试,但它在 sed
中不起作用。
grep -P '(?<=foo)bar' file.txt
通过返回 bar
可以正常工作。
sed 's/(?<=foo)bar/test/g' file.txt
我期待 footest
作为输出,但它不起作用。
I created a test using grep
but it does not work in sed
.
grep -P '(?<=foo)bar' file.txt
This works correctly by returning bar
.
sed 's/(?<=foo)bar/test/g' file.txt
I was expecting footest
as output, but it did not work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
GNU sed 不支持环视断言。您可以使用更强大的语言,例如 Perl,或者可能尝试使用支持Perl 风格的正则表达式。
GNU sed does not have support for lookaround assertions. You could use a more powerful language such as Perl or possibly experiment with
ssed
which supports Perl-style regular expressions.sed 不支持环视,但 choose (我是作者)支持。它使用 PCRE2 语法。
例如:
它的速度可比 sed。
sed doesn't support lookarounds but choose (I'm the author) does. It uses PCRE2 syntax.
For example:
It's speed is comparable to sed.
Powershell 的
-replace
支持前瞻:它会在 7 秒内从空 tsv 单元格中删除 900mb 文件的
\N
。但要小心可能转换的换行符。Powershell's
-replace
supports lookaheads:It removes
\N
from empty tsv cells for 900mb file in 7s. But beware of possibly converted line breaks.请注意,大多数情况下,您可以使用捕获组和替换字符串中的反向引用来避免后向查找(或先行查找):
模拟负后向查找更加微妙,需要多次替换来保护您想要避免的子字符串。
(? 示例:
#
=>##
)。foobar
,=>foob#ar
或ba
=>b #a
)。foob#ar
替换为foobar
(或将b#a
替换为ba
)。##
替换为#
。显然,您还可以在捕获组中的
bar
之前描述除foo
以外的所有内容:但是字符越多,它很快就会变得乏味。
Note that most of the time you can avoid a lookbehind (or a lookahead) using a capture group and a backreference in the replacement string:
Simulating a negative lookbehind is more subtile and needs several substitutions to protect the substring you want to avoid. Example for
(?<!foo)bar
:#
=>##
).foobar
here, =>foob#ar
orba
=>b#a
).foob#ar
withfoobar
(orb#a
withba
).##
with#
.Obviously, you can also describe all that isn't
foo
beforebar
in a capture group:But it will quickly become tedious with more characters.