tags:

views:

2153

answers:

4

I know regex for doing a global replace,

     %s/old/new/g

how do you go about doing an interactive search replace in vim

+3  A: 

I usually use the find/substitute/next/repeat command :-)

/old<CR>3snew<ESC>n.n.n.n.n.n.n.

That's find "old", substitute 3 characters for "new", find next, repeat substitute, and so on.

It's a pain for massive substitutions but it lets you selectively ignore some occurrences of old (by just pressing n again to find the next one instead of . to repeat a substitution).

paxdiablo
I use this as well, even for similar texts. (3cW<texthere><ESC><move to new location>.<move>.<move>.)
strager
Well, I won't be using this 'antipattern' again - see Mark Biek's answer for how to do it the right way.
paxdiablo
It's not an antipattern! It's sweet. And you can search in the opposite direction using N. Really good if you see a word and want to change it. *cwNewText<ESC>N.n.n. (This will jump away from the word under the cursor, but then jump back soon as you have changed the next occurrence.
PEZ
+18  A: 
Mark Biek
+1, I learned something new today! vim has so many hidden secrets.. :)
Marc Novakowski
Indeed! I did not know about the c modifier.
strager
Learning vim commands is a little bit like playing Nethack. You never know what wonders a single character is going to hold.
Mark Biek
Well, bugger me ! I've been using vi for nigh on 30 years and this is the first time I've seen this. That little editor continues to amaze me even after all this time (especially the vim extensions). +1 for making my life easier, where were you 20-odd years ago?
paxdiablo
@Pax Alternating between building a tree fort and writing BASIC programs to print out dirty words :)
Mark Biek
I imagine the "c" is for "confirm"
sirlancelot
I'm honestly not trying to come across as snarky, but all of this could have been found by doing ":help :s" which would have led you straight to ":help :s_flags".
Jeremy Cantrell
+4  A: 

I think you're looking for c, eg s/abc/123/gc, this will cause VIM to confirm the replacements. See :help :substitute for more information.

Logan Capaldo
+1  A: 

If you just want to count the number of occurrences of 'abc' then you can do %s/abc//gn. This won't replace anything but just report the count for the number of occurences of abc.

jinxed_coder