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

How do I replace the next search match and repeat it easily with dot?

Answer

cgn

Explanation

The cgn command combines the change operator with the gn motion to change the next occurrence of your last search pattern. The magic is that the entire operation — search and change — becomes a single repeatable change, so you can hammer . to replace subsequent matches without touching n.

How it works

  • /pattern sets your search pattern
  • gn is a motion that visually selects the next match of the last search
  • c is the change operator
  • Together, cgn deletes the next match and drops you into insert mode
  • Type your replacement text, press <Esc>, then press . to repeat on the next match

Example

Given the text:

foo bar foo baz foo qux

Search for foo with /foo<CR>, then type cgnbar<Esc>. The first foo is replaced:

bar bar foo baz foo qux

Now press . twice to replace the remaining occurrences:

bar bar bar baz bar qux

Tips

  • Unlike :%s/foo/bar/g, cgn + . lets you selectively replace — press . to replace or n to skip
  • Use dgn to delete the next match instead of changing it
  • cgN works in the reverse direction
  • This is faster than n.n.n. because n is baked into the change itself
  • Works with * too: place your cursor on a word, press *, then cgn

Next

How do I edit multiple lines at once using multiple cursors in Vim?