Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert vim / search to search and replace without retyping regular expression

Tags:

When I perform a search and replace in Vim, I like to use the search function (/regex) first to visually test my regex.

Is there a simple way to bring up the expression I wrote in a search and replace command without typing it again?

For example, if I wanted to find the word perform and replace it with execute in the above text, after doing:

/performenter

is there a way to easily insert perform into the search and replace command below?

:%s/perform/execute/g

like image 703
Robert S Ciaccio Avatar asked Jan 11 '11 08:01

Robert S Ciaccio


2 Answers

You can type

/search_term 

and then

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

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

like image 70
Peter Avatar answered Sep 30 '22 17:09

Peter


If you have done a previous search with : /foo

You can simply type : :%s//bar/g

and it will replace every occurrence of foo by bar because Vim understands implicitly you want to replace your previous search. You don't have to retype foo at all.

More generally to reuse a command from history you can use the command q: to bring up the command history and q/ to bring up the search history in a small buffer. Once you're in there you can use every Vim command to paste, cut, recall a previous command by pressing <Enter>...

A great resource for your topic can be found there, this is a webcast about regexp and how to refine them using the command line window.
http://vimcasts.org/episodes/refining-search-patterns-with-the-command-line-window/

like image 29
Xavier T. Avatar answered Sep 30 '22 18:09

Xavier T.