Does lookbehind work in sed?

Matheus Gontijo picture Matheus Gontijo · Sep 30, 2014 · Viewed 12.5k times · Source

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.

Answer

hwnd picture hwnd · Sep 30, 2014

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