10

Often I will do a search to find things in Vim, such as:

/-some-regex-here

And after seeing what if grabs and iterating through a few of the results, I want to do a find-replace. Is there a way to convert the / to a : command? Or do I have to esc and then press : and re-type (or copy-paste) the command again?

3 Answers 3

18

In command-line, you can use ctrl-r (see :h c_ctrl-r) to start inserting the content of a register.

In your case, you could paste the content of the last search with:

<c-r>/

Another way would be to use :h incsearch to show the matches as you type your search (in a / search, or a :s command, and so on), so you don't need to "check" your regex before using it in a substitute command.

2
  • that's perfect, thank you for this. I suppose it's the same if I have a command and want to paste it into a search, I could do <c-r>: ?
    – David542
    Jun 10, 2020 at 6:11
  • Indeed. You should definitely check :h c_ctrl-r ;)
    – Biggybi
    Jun 10, 2020 at 6:14
22

You could just do:

%s//REPLACEMENT/

From the docs:

If the {pattern} for the substitute command is empty, the command uses the pattern from the last substitute or :global command. If there is none, but there is a previous search pattern, that one is used.

A example can be found with :h :s_r and then a few lines down, beginning with "For :s with an argument this already happens:". The quote above is further down in the text.

1
  • This is exactly what I do in the situation the OP describes. I sometimes leverage an empty pattern the same way in a :global, too. Jun 10, 2020 at 22:57
2

Just to show another way in addition to the already existing answers:

In both the / and : command modes, you can press ctrl-f to essentially open the respective history as a new temporary buffer. See :help c_ctrl-f for details.

So, what you could to is the following:

  • enter / ctrl-f (or q/) to open this special buffer for the search mode
  • use any normal mode commands to yank the text you need
  • enter the : command mode and insert the text, either with ctrl-r " or again using ctrl-f

Of course, ctrl-r / is quicker for this particular use case, but the ctrl-f method is more general, so maybe it's useful to someone who finds this question.

3
  • 1
    neat, but then if I'm in search, how to get the most recent : commands, or vice-versa?
    – David542
    Jun 11, 2020 at 20:37
  • 1
    Actually that would q/ in this case, but q: works for the command line
    – D. Ben Knoble
    Jun 12, 2020 at 2:59
  • This is useful when one types /%s/foo/bar and then realizes he has mistankenly used / instead of :.
    – Quasímodo
    Aug 15, 2020 at 13:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.