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
/patternsets your search patterngnis a motion that visually selects the next match of the last searchcis the change operator- Together,
cgndeletes 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 ornto skip - Use
dgnto delete the next match instead of changing it cgNworks in the reverse direction- This is faster than
n.n.n.becausenis baked into the change itself - Works with
*too: place your cursor on a word, press*, thencgn