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?
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.
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.
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.
You can use \<
to match the beginning of a word and \>
to match the end:
%s/\<word\>/newword/g
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With