Skip to main content
edited tags
Link
Gilles 'SO- stop being evil'
  • 865.4k
  • 205
  • 1.8k
  • 2.3k
Source Link
Question Overflow
  • 4.9k
  • 19
  • 64
  • 89

Search and replace strings that are not substrings of other strings

I have a list of replacements like so:

search_and -> replace
big_boy -> bb
little_boy -> lb
good_dog -> gd
...

I need to make replacements for the above, but at the same time avoid matching strings that are longer like these:

big_boys
good_little_boy

I tried this:

sed -i -r "s/$(\W){search}(\W)/$\1{replacement}\2/g"

But the above does not work when the string ("good_dog" in this case) occurs at the end of a line like so:

Mary had a 'little_boy', good_little_boy, $big_boy, big_boys and good_dog

Mary had a 'lb', good_little_boy, $bb, big_boys and good_dog

And I doubt the above would work when the string occurs at the start of the line too. Is there a good way to do the search and replacement?