Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VIM find all occurrences and replace with input

Tags:

vim

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.

like image 628
ExcellentAverage Avatar asked Mar 10 '16 11:03

ExcellentAverage


2 Answers

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.

like image 123
Luc Hermitte Avatar answered Nov 09 '22 07:11

Luc Hermitte


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.

like image 36
dlmeetei Avatar answered Nov 09 '22 07:11

dlmeetei