Use sed to find whole word and replace

command linereplacesed

I have the following block of text in a file:

test3.legacy test4.legacy test3 test3.kami

I only want to search for test3 as a whole and replace it with nothing. Unfortunately, all my attempts have removed test3 from test3.legacy and test3.kami. I've tried:

sed 's/^test3://g' myfile.txt
sed 's/\btest3\b//g' myfile.txt
sed 's/\<test3\>//g' myfile.txt

without any luck. Any ideas how I can resolve this please?

EDIT: Most attempts have resulted in the following: .legacy test4.legacy .kami

Best Answer

Is this what you want?

$ sed 's/\(^\| \)test3\( \|$\)/\1/g' file
test3.legacy test4.legacy test3.kami

This say

substitute
   (^ start of line OR space)
   test3
   (space OR end of line)
with match 1 (AKA space or start of line)

Update:

And as so elegantly put by the good @Stephane Chazelas this would not take care of certain cases. Also emphasize on the portability part. See answer below.

A GNU variant could, (hopefully), be:

sed 's/\(^\| \)\(test3\( \|$\)\)*/\1/g'
# Or perhaps:
sed 's/\(^\| \)\(test3\( \|$\)\)\+/\1/g'

taking care of repetitive matches. Optionally one would take care of multiple spaces etc as well. Depending on input.

EOUPD


As an alternative perhaps (only meant as a starting point):

sed 's/\Wtest3\W/ /g'

Not this I assume:

$ sed 's/test3\.\?[^ ]* *//g' file
test4.legacy
Related Question