Home > database >  How can I replace the string that I just searched without retyping it in vim?
How can I replace the string that I just searched without retyping it in vim?

Time:11-24

In vim, /string is to search a string, :s/string/replace is to replace string with replace.

By typing / and hitting up/down, one can view history searches. Same with replacing.

But is there a way to make replacing use history of searching, that is to replace the string that has just been searched for?

I'm trying to use regex to replace /****ABC****/ comments with /**** ABC *****/ to pass coding style check, the number of * is variable and ABC contains several words.

I used searching instead of replacing to try to find the right regex, which has a lot of \\*[].

(I'd like to paste my result here but it keeps pompting up uploading image box...)

I do understand that I can copy the regex somewhere else and paste it back after typing :%s/, but what if I'm using non GUI vim? Is there a feature that helps with this or will I have to write the regex on paper?

CodePudding user response:

Whenever search pattern is omitted the last one will be used. So after searching for any "foobar" with "slash" you can also "substitute" all of your "foobar"s by specifying empty search pattern.

Also, the last search pattern used is available as the "slash" register. So you can input its contents into the cmdline by pressing "ctrl-r" followed by "slash" key. All other register-related stuff works too.

CodePudding user response:

If you use an empty search pattern (:%s//), it should use the pattern in the search register. The help for the substitute command (:h :s, and scroll down to the prose beneath the commands and flags) implies that it works differently:

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.

That is, it says that it would use the last :s pattern if there was one and only if there isn't would it use the last /search pattern, but in reality, it just uses the last search pattern.


You can also use <c-r>/ (control-r then a slash) while you have your cursor after the "/" in the :%s/ command and it will paste the last search pattern into the command.

  • Related