How do I selectively replace occurrences one at a time, choosing to apply or skip each match?
Answer
n.
Explanation
The n. workflow is a powerful alternative to :s///gc for selectively replacing matches. Instead of being prompted for each occurrence, you use Vim's dot-repeat to decide on the fly — press . to apply your last change, or n to skip ahead.
How it works
The technique builds on three primitives:
/pattern— set the search register to highlight all matchescgn— change the next match (gnselects the next search match as a text object), dropping you into insert mode.— repeat the last change, which applies the same text replacement to the next highlighted matchn— jump to the next match without applying the change (effectively "skip")
The crucial insight is that after a cgn edit, . will:
- Jump to the next match (via the embedded
gnmotion) - Delete it
- Insert your replacement text
All in a single keystroke.
Example
foo bar foo baz foo
/foo<CR>— search forfoocgnthen typequxthen<Esc>— change first match.— replace nextfoowithquxn— skip the thirdfoo
Result:
qux bar qux baz foo
Tips
- This is strictly more powerful than
:s///gcbecause your replacement can use any insert-mode editing (paste from register, abbreviations, completion). - Start with
*instead of/pattern<CR>to instantly search the word under the cursor. - Use
N.to walk backwards through matches. - Combine with
:%norm @qwhen you need the same transformation across many non-contiguous lines.