60
votes

To find and replace all instances of a word in vim, I use

%s/word/newword/g

How do I change this so that it only finds instances of "word" that are whole words?

3
possible duplicate of Searching word in vim? - Nathan Fellman

3 Answers

108
votes

You can use \< to match the beginning of a word and \> to match the end:

%s/\<word\>/newword/g
19
votes

For case-sensitive replace.. you can use "\C"

:%s/\<word\>\C/newword/g

It replaces only "word" with newword leaving others like Word,WORD... unreplaced.

0
votes

For PCRE compatible search and replace, you can use the perldo or rubydo commands as described here: http://vim.wikia.com/wiki/Perl_compatible_regular_expressions

For example:

:perldo s/\bword\b/newword/g