Search and Replace in Vim

Search and replace is pretty straightforward in Vim. But it’s done in command mode rather than with a nifty little search and replace dialog. Type : to get into command line, and then if you want to replace foo with bar, you do:


However, this simple syntax is very limited. It will just replace the first occurrence of foo with bar - on the current line you’re on. If you want to replace all the instances of foo on the line, add a g at the end:


A more common use case is that you want to replace every occurrences of foo in the current file with bar. To do that, use %s:


That’s a lot to remember and type. OK, it’s not really that much, but if we can make it easier, why not? Here’s a mapping that makes it a little better, IMO:

nnoremap <Leader>rr :%s//g<Left><Left>

This is mostly a straight up and really simple macro-type mapping. It just takes you into command line and then types out everything you need except the terms you want to find and replace. And then it adds two <Left>s that move the cursor back in between the two forward slashes. After typing the shortcut, you just need to type the search word, a forward slash and the replace word. Pretty simple.

But we can go one further. Since the word you want to replace is usually right there in front of you, it would be great if we could grab it out of the buffer, rather than retyping it by hand. We do that with a special control key combo, <c-r><c-w>. This stands for the word currently under the text cursor in the current buffer. Here’s that in use:

nnoremap <Leader>rw :%s/<c-r><c-w>//g<left><left>

This is essentially the same as the first, but it auto-inserts the search term that your cursor is on, and the middle forward slash. All you need to do now is type the word you want to replace it with and hit enter.