3

I often find myself doing an interactive search and replace for a string that may be either a whole word or a partial word, such as changing bar to jaz and also foo_bar_blah to foo_jaz_blah.

So I can't just do cw. But if I do for example c/_<CR> then I've lost bar as the search pattern. How can I change just the current instance of the search pattern and retain that search pattern?

1
  • 3
    c/_<cr> is perhaps better written ct_.
    – Mass
    Sep 13, 2017 at 1:47

2 Answers 2

8

To change the current match (or next match, if the cursor is not on a match) use cgn or gnc. Alone, gn visually selects the match.

3

Here is the answer I finally found after sifting through the vimdoc site, specifically the chapter on patterns scrolling a few paragraphs below the section labeled *search-offset*

An example of how to search for matches with a pattern and change the match
with another word:
    /foo<CR>    find "foo"
    c//e        change until end of match
    bar<Esc>    type replacement
    //<CR>      go to start of next match
    c//e        change until end of match
    beep<Esc>   type another replacement
                etc.

The important thing is NOT to use n to move to the next instance, because doing so will put you at the END of that instance. You must use //<CR> as shown. You can use . as usual if you just want to repeat the previous c//e change.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.