Repeat the last substitution

3.7
(226)

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 :%&&.

How useful was this tip?

Average rating 3.7 / 5. Vote count: 226

No votes so far! Be the first to rate this tip.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Written by

Colin Bartlett

92 Posts

Vim enthusiast and software developer for more than 20 years.
View all posts

Leave a reply

Your email address will not be published. Required fields are marked *