7

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.

2 Answers 2

15

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Worked like a charm. Is exactly what I was looking!
I could be wrong but shouldn't it be : %s/value_one/\=input('replace <'.submatch(0).'> with: ')/gc. Double slash after value_one gives me 'E488: Trailing characters'.
3

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.

3 Comments

Thanks for the response. I prefer the answer from Luc Hermitte because it's abit more elegant in my opinion. Thanks for the effort though
Absolutely , no problem. Me too
You can also use the gn motion. e.g cgn then . to repeat (No n!). For more help see :h gn and this Vimcasts episode: Operating on search matches using gn

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.