Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does lookbehind work in sed?

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.

like image 926
Matheus Gontijo Avatar asked Sep 29 '14 23:09

Matheus Gontijo


People also ask

Does SED support Lookbehind?

I created a test using grep but it does not work in sed . This works correctly by returning bar . I was expecting footest as output, but it did not work. sed does not support lookaround assertions.

Does SED support lookahead?

Note that SED doesn't have lookahead and therefore doesn't support the regex feature you were trying to use. It can be done in SED using other features, as others have mentioned.

Can I use Lookbehind regex?

The good news is that you can use lookbehind anywhere in the regex, not only at the start. If you want to find a word not ending with an “s”, you could use \b\w+(? <! s)\b.

Does grep support Lookbehind?

find (both the GNU and BSD variants) do not support lookahead/lookbehind. GNU grep only supports the POSIX basic and extended regular expression variants as well as a couple of others.


1 Answers

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 
like image 58
hwnd Avatar answered Sep 28 '22 12:09

hwnd