Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the last expression used in search in Vim?

Tags:

vim

When doing more complicated search & replace operation in Vim I often try it out in search and only if it finds what I expect I use search & replace.

Is there a way how to access the last value from search and put it into search & replace or alternatively, to put this last value into a register?

like image 865
ps-aux Avatar asked Jun 21 '14 13:06

ps-aux


People also ask

How do I view previous searches in Vim?

Search History Vim keeps track of all the search operations you made in the current session. To browse the search history, press / or ? and use the arrow up/down keys to find a previous search operation. To run the search, simply press Enter.

How do I find all words that start with I in Vim?

Simply move the cursor anywhere within the word, then press * to search for the next occurrence of that whole word. Vim inserts \< and \> automatically (see searching). The pattern \<i finds all words that start with "i", while i\> finds all words that end with "i".

How to search for a pattern in vim/vi text editor?

To switch to normal mode, press Esc. There are two ways to search for a pattern of numbers or letters in the Vim/Vi text editor. 1. Search forward for the specified pattern 2. Search backward for the specified pattern The direction is determined in relation to the cursor position.

How to disable case sensitive searches in Vim?

To search for pattern in all cases, you need to disable case using set command in vim. Type the following command in vim to disable case sensitive searches. Next, again do search for some text, you will find that search selection is ignoring the case.


2 Answers

From the VIM wiki page:

:%s//<c-r>//g
    Replace each match of the last search pattern with the / register (the last search pattern). 
    After pressing Ctrl-R then / to insert the last search pattern (and before pressing Enter to perform the command), you could edit the text to make any required change. 
like image 129
Luke Peterson Avatar answered Nov 13 '22 01:11

Luke Peterson


If you don't need to edit the search regex you can omit it and vim will use the last search for the pattern.

:%s//<replacement>/

From :h :s | /If the {pattern}

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.  With the [r] flag, the
command uses the pattern from the last substitute, `:global`, or search
command.
like image 39
FDinoff Avatar answered Nov 13 '22 01:11

FDinoff