How do I repeat the last substitute command quickly?
Answer
&
Explanation
The & command in normal mode repeats the last :s substitution on the current line. For repeating across the entire file with the same flags, use g&. This saves you from retyping or recalling complex substitute commands.
How it works
&repeats the last:scommand on the current line, but without the original flagsg&repeats the last substitution across the entire file with the original flags — it is equivalent to:%s//~/&:&&repeats the last substitution on the current line with the original flags (likegandc):'<,'>&repeats it over a visual selection
Example
Given the text:
foo bar foo
foo baz foo
foo qux foo
Run :s/foo/CHANGED/g on line 1:
CHANGED bar CHANGED
foo baz foo
foo qux foo
Now move to line 2 and press & — it replaces only the first foo (no g flag). Use :&& instead to keep the g flag and replace all occurrences on that line.
Or simply press g& from anywhere to apply the substitution to every line in the file at once.
Tips
g&is the fastest way to "I should have used%in that substitute" — it retroactively applies to the whole file:&&preserves flags,&does not — this distinction catches many people off guard- In visual mode, select lines and type
:&&to repeat the substitution only within the selection - Combine with
@:to repeat the full last ex command including range and flags