views:

989

answers:

4

Hi,

How do I search and replace whole words using sed? Doing sed -i 's/[oldtext]/[newtext]/g' will also replace partial matches of [oldtext] which I don't want it to do.

Thanks, Kenneth

+6  A: 

\b in regular expressions match word boundaries (i.e. the location between the first word character and non-word character):

$ echo "bar embarassment" | sed "s/\bbar\b/no bar/g"
no bar embarassment
Joakim Lundborg
dang! beat me to it!
Mitch Wheat
+2  A: 
sed -i 's/\b[oldtext]\b/[newtext]/g'
Mitch Wheat
A: 

In one of my machine, delimiting the word with "\b" (without the quotes) did not work. The solution was to use "\<" for starting delimiter and "\>" for ending delimiter.

To explain with Joakim Lundberg's example:

$ echo "bar embarassment" | sed "s/\<bar\>/no bar/g"
no bar embarassment
ArunSaha
A: 
$ echo "bar embarassment"|awk '{for(o=1;o<=NF;o++)if($o=="bar")$o="no bar"}1'
no bar embarassment
ghostdog74