How do I use cgn to repeat a change on every search match?
Answer
/pattern<CR>cgnreplacement<Esc>.
Explanation
The gn text object selects the next search match, and cgn changes it. After the first change, pressing . automatically finds and changes the next match. This is the modern Vim alternative to search-and-replace for interactive, selective changes.
How it works
/pattern<CR>— search for the patterncgn— change the next match (gn selects it, c changes it)- Type the replacement text and press
<Esc> .— repeat: finds next match AND applies the same changento skip a match,.to change it
Example
Before:
const foo = getFoo();
const bar = foo.bar;
return foo;
Search: /foo<CR>
cgnmyVar<Esc>
. to change next, n to skip
After (selectively):
const myVar = getFoo();
const bar = foo.bar; (skipped with n)
return myVar; (changed with .)
Tips
- Unlike
:%s, this is interactive — you decide each replacement individually dgndeletes the next match instead of changing itgnin visual mode extends the selection to include the next match- Works with
*search: press*on a word, thencgnto start replacing