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

How do I replace matches one-by-one using cgn and dot-repeat?

Answer

*cgn

Explanation

Global substitution is fast, but sometimes you need selective control over each occurrence. The * plus cgn workflow lets you step through matches and decide replacement incrementally, while still staying very fast through dot-repeat. This is ideal when many matches should change, but a few should be skipped because of context.

How it works

  • * searches forward for the word under cursor and sets the search register
  • cgn changes the next search match and enters Insert mode
  • Type the replacement text, press <Esc>, then press . to repeat the same change on the next match
*
cgnnew_text<Esc>
.

Example

Given this code, with cursor on the first count:

count = count + 1
count_total = count_total + 1
count = count + 1

Use *, then cgncounter<Esc>, then . to continue on the next exact match. You get selective, context-aware replacements without opening a :%s prompt.

Tips

  • Use n to skip one match before pressing .
  • gN and cgN let you walk backward through matches
  • Add :set hlsearch to keep match locations visible while you iterate

Next

How do I make Vim transparently edit .gz files using built-in tooling?