Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and replace whole words in vim

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?

like image 408
neuromancer Avatar asked Nov 22 '09 11:11

neuromancer


People also ask

How do I find and replace a word in Vim?

Basic Find and Replace In Vim, you can find and replace text using the :substitute ( :s ) command. To run commands in Vim, you must be in normal mode, the default mode when starting the editor. To go back to normal mode from any other mode, just press the 'Esc' key.

How do I search a whole word in Vim?

To search using Vim/vi, for the current word: In normal mode, you can search forward or backward. One can search forward in vim/vi by pressing / and then typing your search pattern/word. To search backward in vi/vim by pressing ? and then typing your search pattern/word.

How do I replace a word in vi editor globally?

The % is a shortcut that tells vi to search all lines of the file for search_string and change it to replacement_string . The global ( g ) flag at the end of the command tells vi to continue searching for other occurrences of search_string . To confirm each replacement, add the confirm ( c ) flag after the global flag.


1 Answers

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

%s/\<word\>/newword/g 
like image 142
sth Avatar answered Sep 20 '22 05:09

sth