Does lookbehind work in sed?

浪子不回头ぞ 提交于 2019-12-17 16:13:00

问题


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.


回答1:


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.

perl -pe 's/(?<=foo)bar/test/g' file.txt



回答2:


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:

sed 's/\(foo\)bar/\1test/g' file.txt


来源:https://stackoverflow.com/questions/26110266/does-lookbehind-work-in-sed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!