I just googled something I’ve always wanted to know how to do in vim, and was surprised how quickly I found the answer.

In vim, there are separate modes for searching and commands. This generally works well as they have separate completion buffers and since I do them a lot, it keeps my command history from cluttering up my search history and vice versa. The area where I’ve wished that they were unified is when I want to convert from a search to a substitution expression. Normally in vim you do search expressions in search mode and command expressions in command mode. For example, if I wanted to search for trailing whitespace I might type:

/\s\s*

If I want to replace it with an empty string through the whole file I might type:

:%s/\s\s*//g

I can’t remove the / at the front of the command line with a backspace and replace it with a colon, so until I learned the tip I’m about to reveal I had to retype it. No longer.

The StackOverflow answer I found for the query, Convert vim / search to search and replace without retyping regular expression, suggests this remarkably simple technique:

You can type

/search_term

and then

:%s/<ctrl-r>// etc

where you actually press ctrl+r and then / to insert the search term.

It works! No longer do I desire for search and command modes to be unified.

4 thoughts on “converting a search to a replace in vim

  1. While `ctrl-r /` certainly has its uses, in the example you’ve given, you could just as well leave the search field of the substitute command empty. When no pattern is provided for the substitute command, it will use the last search pattern.

  2. Drew,

    Thanks! That’s the other popular answer in Stack Overflow too. I also remember reading it, ages ago, but somehow I forgot it. The ctrl-r / trick is completely new to me, though.

Comments are closed.