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 registercgnchanges 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
nto skip one match before pressing. gNandcgNlet you walk backward through matches- Add
:set hlsearchto keep match locations visible while you iterate