VimTrick: Repeat the last substitution
Vim has several useful ways to repeat the last substitution
Developing efficient workflows in Vim is all about repetition, first and foremost by using .
to repeat the last command. But Vim can also repeat your last substitution. Here’s a few options with subtle differences:
:& - Repeats last substitution but resets the flags. Also works with just :s.
:&& - Repeat last substitution with the same flags.
:%& - Repeat last substitution on entire file, reset flags.
:%&& - Repeat last substitution on entire file, keep flags.
And here’s a bonus tip that works from normal mode, so even less typing:
& - From normal mode, this repeats the last substitution but resets flags.
Why would you want to reset the flags when re-running a substitution? After all, the most common flag is /g which is necessary to change all the references on a line at the same time.
Here’s a great reason: You may have read our previous tip about counting occurrences without changing them. We can combine these two tips together to first count the number of occurrences of a pattern and then change them:
:%s/something/newthing/gn
:%&g
In the screencast below, we demonstrate this process. First, we make a substitution but only count the number of occurrences rather than make the replacements. Then we repeat it and actually make the replacements. Finally, we go to another file and repeat the substitution with :%&&
.

A quick note on the screencast:
We’re experimenting with video… what do you think? We are aiming to keep them very quick and bite size but the video format allows us to do more than a gif, which frustratingly repeats and has no pause. What do you think? Email us!
Was this useful? Help us improve!
With your feedback, we can improve VimTricks. Click a link to vote: