How do I repeat the last substitute command preserving its flags?
Answer
:&&
Explanation
After running a :s/pattern/replacement/g command, you often need to repeat it on another line or range. The :& command repeats the last substitution, but it drops the original flags. Using :&& repeats it with the original flags intact, which is almost always what you want.
How it works
:&— repeat the last:scommand on the current line, but without any flags (nog,c,i, etc.):&&— repeat the last:scommand on the current line with the original flags preserved:%&&— repeat the last:swith original flags across the entire file:'<,'>&— repeat on a visual selection (add&for flags)
Example
Suppose you run this substitution:
:s/foo/bar/gi
Then move to another line:
:& " runs :s/foo/bar/ (flags dropped — only replaces first match, case-sensitive)
:&& " runs :s/foo/bar/gi (flags preserved — replaces all, case-insensitive)
Tips
- In normal mode,
&is equivalent to:s(repeats without flags) — use:&&explicitly when flags matter - Combine with a range to apply across multiple lines:
:5,20&& - The
g&normal-mode shortcut runs:%s//~/&which repeats the last substitute across the whole file with flags