For example I have some 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 by :%s/substitute/sub/gc
I can interactively search/replace. If I press 'n' it goes to the next matched pattern, how can I undo 'n'? or search backwards?
In usual search mode /search_word
we can skip by 'n' and 'N' is there something similar for substitute - :%s/substitute/sub/gc
?
Press <shift-N> to go back to the previous occurrence of your find term.
We can then type in the cgn command combo: cgn. This Vim editor command finds the last thing we searched for, delete it, and then put us into insert mode. While in insert mode, let's type in the word “tutorial”.
Change and repeat Search for text using / or for a word using * . In normal mode, type cgn (change the next search hit) then immediately type the replacement. Press Esc to finish. From normal mode, search for the next occurrence that you want to replace ( n ) and press . to repeat the last change.
Mathias Bergert's answer does the trick, if you just need do simple single word replacement, and the replacement text is always fixed. Well perhaps this is satisfied with 70% of our daily editing. If you need the power of s/.../.../
for your substitution needs, it may be not sufficient. For example, multiple words replacement, the back reference or the function expressions in the replacement part.
What I can think of is, first do a:
:s/substitute/sub/c
note, without % range
and g
flag.
then you just:
n
or N
for for/backwards search, &
, u
The key is, &
will redo last substitution.
In this way, you can do more complex substitutions, which is hard for the simple cw
like:
s/f../&, /
add a comma after all fxx
words (foo, far, fur...)s/\v(foo)(\d+)/\=submatch(1).(submatch(2)+1)/
increment number after foo
Personally I prefer the .
command over the substitute c flag, this adds much more flexibility.
Do something like this:
/substitute<cr>
cwsub<esc>
Search for "substitute", then cw
(change word) to "sub" (<esc>
exits insert mode)
Now you can use n
and N
to move and the dot .
command to replace the "substitute" to "sub". With u
you can even undo the last one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With