ExcellentAverage
ExcellentAverage

Reputation: 451

VIM find all occurrences and replace with input

Is it possible to search a file for the occurrences of a specific word and ask the user for input to replace this word with. Do the same thing over again, either typing in a new replacement or using something from your history, until all the words are replaced or the user quits. Keep in mind that I want to have the choice to skip over words I don't want to replace.

Just using

:%s/value_one/value_two/gc

would mean I have to execute this command for each different replacement I have in mind. Is this possible or is there something wrong with this workflow. I would use this when pasting boilerplate code that only need one variable to be changed.

Upvotes: 7

Views: 1084

Answers (2)

Luc Hermitte
Luc Hermitte

Reputation: 32946

You're looking for:

%s/value_one/\=input('replace <'.submatch(0).'> with: ')/gc

:h :s\= and :h input(). You should be able to provide a default value for input if you wish.

Upvotes: 15

dlmeetei
dlmeetei

Reputation: 10381

This might not be the perfect, Just sharing what I used.

This assumes that :set hl is set already. Pressing * would search for the word under cursor. Bring the cursor to your word. But I usually use gd instead of *.

Then, change it using ciw to replacement word. Then Esc. We can now go to next occurence by n.

If this need to be changed to the same word, then pressing . does that. If not, you can change to new value by using ciw again.

If you don't intend to change next occurence, just skip it by pressing n, which takes to next occurence.

This seems little manual, but this gives a conservative control over my edit.

Upvotes: 3

Related Questions