How can I switch from direct to reverse in interactive search / replace regex in Vim?

For example, I have text:

'y' to substitute this match 'l' to substitute this match and then quit ("last") 'n' to skip this match <Esc> to quit substituting 'a' to substitute this and all remaining matches {not in Vi} 'q' to quit substituting {not in Vi} 

and :%s/substitute/sub/gc I can interactively search / replace. If I press 'n' it will go to the next template, how can I cancel 'n'? or search back?

In the normal search mode /search_word we can skip "n" and "N" is there something similar for substitution - :%s/substitute/sub/gc ?

+5
source share
3 answers

Matthias Bergert's answer does the trick if you just need to replace one word and the replacement text is always corrected. Perhaps this is satisfied with 70% of our daily editing. If you need power s/.../.../ for your replacement needs, this may not be enough. For example, substitution of several words, backward link or expressions of functions in the replacement part.

I might think first do a:

 :s/substitute/sub/c 

note without % range and g .

then you simply:

  • press n or n to search / reverse search,
  • if you think the match should be replaced, click & ,
  • If you make a mistake, press u

Key, & will perform the last replacement.

This way you can perform more complex substitutions, which is difficult for a simple cw like:

  • s/f../&, / add a comma after all the words fxx (foo, far, fur ...)
  • s/\v(foo)(\d+)/\=submatch(1).(submatch(2)+1)/ increment number after foo
  • etc.
+7
source

Personally, I prefer . command over the replacement flag c, this adds much more flexibility.

Do something like this:

 /substitute<cr> cwsub<esc> 

Find "replace", then cw (change the word) to "sub" ( <esc> exits insert mode)

Now you can use n and n to move, and the command points . replace "substitute" with "under." With u you can even undo the last one.

+6
source

I made a plugin a while ago just for that. It is more extensive than other answers, so if you are ok with the plugins, you might like

https://github.com/sosmo/vim-easyreplace

Basically, it performs your substitution in each match, one after another, when you press ctrl-n.

0
source

All Articles