How do I search and replace with confirmation for each match?
Answer
:%s/old/new/gc
Explanation
Adding the c flag to a substitute command makes Vim pause at every match and ask you whether to replace it. This gives you surgical control over bulk replacements without blindly changing things you did not intend to touch.
How it works
:%s/old/new/greplaces all occurrences in the file- Adding
cat the end (gc) triggers interactive confirmation - At each match Vim asks
replace with new (y/n/a/q/l/^E/^Y)?
The confirmation options:
| Key | Action |
|---|---|
y |
Replace this match |
n |
Skip this match |
a |
Replace all remaining matches |
q |
Quit substitution |
l |
Replace this match and quit ("last") |
^E |
Scroll up |
^Y |
Scroll down |
Example
Given the text:
foo is great
foo is fast
foo is fun
Running :%s/foo/bar/gc will highlight the first foo and prompt you. Press y for line 1, n to skip line 2, and y for line 3:
bar is great
foo is fast
bar is fun
Tips
- Combine with
\<and\>for whole-word matching::%s/\<foo\>/bar/gc - Use a visual selection first to limit the scope: select lines, then
:'<,'>s/old/new/gc - If you realize you want to replace everything, press
ato skip the remaining prompts - Press
lto replace just one more and stop — handy when you spot the last one you care about