vimtricks.wiki Concise Vim tricks, one at a time.

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 pattern
  • cgn — 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 change
  • n to 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
  • dgn deletes the next match instead of changing it
  • gn in visual mode extends the selection to include the next match
  • Works with * search: press * on a word, then cgn to start replacing

Next

How do I return to normal mode from absolutely any mode in Vim?