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

How do I change each occurrence of a search match one at a time, confirming each with the dot command?

Answer

cgn...{text}<Esc>.

Explanation

The cgn + . workflow is a surgical alternative to :%s/old/new/gc. Search for a pattern, then cgn selects the next match as a text object and opens change mode. After typing your replacement and pressing <Esc>, the . command repeats the entire cgn{text} change on the next match, while n skips a match without changing it. This gives you per-match control without the awkward confirm prompt of :%s///gc.

How it works

  • /pattern<CR> sets the search pattern (or use * to search for the word under cursor)
  • c is the change operator; gn is the text object that selects the next match
  • Together, cgn deletes the match and enters insert mode
  • After <Esc>, Vim records the entire cgn{replacement} sequence as a repeatable change
  • . applies that same change to the next match; n moves to the next match without changing it

Example

You want to rename foo to bar selectively:

/foo<CR>    " search for foo
cgn         " change next match (enters insert mode)
bar<Esc>    " type replacement and exit insert mode
.           " change next match
n           " skip this one
.           " change the one after

Tips

  • Unlike :%s/foo/bar/gc, there's no y/n/a/q prompt — use . to apply and n to skip
  • Works with complex replacements that aren't simple string swaps
  • Use gN instead of gn to operate on the previous match
  • Combine with a count: 3. to apply the change to the next 3 matches in sequence

Next

How do I control how many lines Ctrl-U and Ctrl-D scroll?