MP Raju
MP Raju

Reputation: 1

sed replace patterns except when it matches some specific pattern

Does anybody know how to replace patterns except when it matches some specific pattern using sed?

For example, all "foo" should be replaced except for "food"

Upvotes: 0

Views: 1868

Answers (2)

potong
potong

Reputation: 58488

This might work for you (GNU sed):

sed -r ':a;s/foo([^d]|$)/xxx\1/;ta' file

This replaces foo and the following character unless it is a d.

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 247042

If you're open to alternatives to sed, perl's lookaround assertions are helpful:

$ perl -E '$s="foofoofoodfoofood"; $s=~s/foo(?!d)/bar/g; say $s'
barbarfoodbarfood

Upvotes: 1

Related Questions