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?

David542
  • 2,445
  • 14
  • 50

3 Answers3

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.

Ralf
  • 9,197
  • 1
  • 11
  • 30
  • 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. – John Bollinger Jun 10 '20 at 22:57
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.

Biggybi
  • 2,740
  • 9
  • 29
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.

wrtlprnft
  • 173
  • 2
  • 8