Unix & Linux
regular-expression vim
Updated Sun, 26 Jun 2022 04:39:15 GMT

vim: use string from search in replace command

I often use vim / search command to verify my regular expressions (just to see what it matches). After that I usually use the :%s replace command, where I use that regexp from search as a string to be replaced, e.g. I first look for such string:


It matches exactly what I want, so I do my replace:


But I have to write again entire regexp here. Usually that regexp is much longer, that's why I'm looking for solution:

Is there any existing shortcut or vim script for pasting that search pattern directly into replace command?

I use vim in terminal (no gvim).


In general, an empty regular expression means to use the previously entered regular expression, so :%s//\1/g should do what you want.

Comments (5)

  • +0 – Woah, it's that easy! Exactly what I needed, thanks. — Mar 12, 2011 at 23:49  
  • +0 – Also, if you want to verify or modify the last used pattern, you can use Control-r then / to insert the contents of the search pattern register (/) directly into a partially typed command line (e.g. right after :%s/). — Mar 13, 2011 at 05:10  
  • +0 – thats very useful hint as well. Thanks @Chris! +1 — Mar 13, 2011 at 10:38  
  • +0 – What if I want to follow up "\1" with a number like say 23? How do I avoid it being interpreted as "\123"? — Jul 28, 2015 at 15:22  
  • +1 – @Champ As back references only go up to \9, there is no ambiguity. — Aug 25, 2017 at 12:47