7

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?

14

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 to the pattern as you type (in a search, or a :s command, and so on), so you wouldn't have to "check" for your regex before using it in a substitute command.

| improve this answer | |
  • 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 at 6:11
  • Indeed. You should definitely check :h c_ctrl-r ;) – Biggybi Jun 10 at 6:14
19

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.

| improve this answer | |
  • 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 at 22:57
0

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.

| improve this answer | |
  • 1
    neat, but then if I'm in search, how to get the most recent : commands, or vice-versa? – David542 Jun 11 at 20:37
  • 1
    Actually that would q/ in this case, but q: works for the command line – D. Ben Knoble Jun 12 at 2:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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