sed replace exact match of the word

4.7k views Asked by At

I a situation, where i have to replace exact same word in a string. For example :

String: Dog DogCat CatDog Dog Cat Cdog ratdog Dog dog

I tried following cmd, but it is not working, i use AIX:

echo "Dog DogCat CatDog Dog Cat Cdog ratdog Dog dog " | sed  -i 's/"\<Dog\>"/[[:blank:]]/' 

expected Output: DogCat CatDog Cat ratdog

Please help me out.

-Hanmant

2

There are 2 answers

0
geirha On BEST ANSWER

First of all, sed -i 'script' file only works if you have GNU sed. Do you really have GNU sed installed on AIX? I doubt it. Also, -i makes no sense in this context anyway. You're modifying a stream coming from a pipe, not file.

Second, POSIX does not specify \< and \>, though I know at least GNU sed and Solaris sed accept them. BSD sed on the other hand, use [[:<:]] and [[:>:]] to match the same.

If the sed on AIX accepts \< and \> to match start-of-word and end-of-word respectively, AND it is POSIX compliant, then this might do what you want:

echo "Dog DogCat CatDog Dog Cat Cdog ratdog Dog dog " | sed 's/\<[Dd]og\>//g'

I also don't understand why you put a regex construct like [[:blank:]] in the replacement part of the s command. The replacement part is not a regular expression.

For a POSIX compliant version:

echo ... | sed 's/ [Dd]og  */ /g; s/^[Dd]og  *//; s/ [Dd]og$//'
1
Renato Reis On

Do you know http://regex101.com/ ? There you can test your regex strings directly... Try replacing [blank] with /[[:space:]]+/