Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace text using lookahead regex

I am trying to modify a few lines of a text file.

# cat example.txt
tested
tests
testing

If the word 'test' is not followed by 'ed' or 's' then change it to word 'work'. The following exmpression is working as expected:

test(?!ed|s)

But it does not work in sed as like this...

# sed -r 's/test\(?!ed\|s\)/work/g' example.txt
tested
tests
testing

The expected output is:

tested
tests
working

I guess sed does not support lookahead or lookback. Is there any other easy linux command for this?

like image 331
shantanuo Avatar asked Nov 24 '25 17:11

shantanuo


1 Answers

perl -pe's/test(?!ed|s)/work/g' filename

For Unicode (non-ASCII) text we need to enable support for it

perl -Mutf8 -CSAD -pe'...' filename

Here the utf8 pragma is needed if there are literal non-ASCII characters in the source, while the other flags can be seen under command switches in perlrun

like image 167
zdim Avatar answered Nov 26 '25 13:11

zdim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!