vimtricks.wiki Concise Vim tricks, one at a time.

How do I repeat my last substitution across the entire file?

Answer

g&

Explanation

The g& command repeats the last substitute command across the entire file. It's equivalent to :%s//~/& — reusing the last pattern, replacement, and flags but applying them to every line.

How it works

  • & repeats the last substitution on the current line only
  • g& repeats the last substitution on all lines in the file
  • Both preserve the original flags (like g, i, c)

Example

You run a substitution on a visual selection:

:'<,'>s/foo/bar/g

Then you realize you want to apply the same change to the entire file:

g&

This is equivalent to :%s/foo/bar/g.

Related commands

&        " Repeat last :s on current line (without flags)
:&&      " Repeat last :s on current line (with flags)
g&       " Repeat last :s on entire file (with flags)
:~       " Repeat last :s with last search pattern
@:       " Repeat last Ex command (any command, not just :s)

Tips

  • g& is a massive time-saver when you test a substitution on one line first, then want to apply it everywhere
  • The difference between & and :&& is subtle but important: & drops flags, :&& keeps them
  • g& always uses the flags from the original command
  • This is documented under :help g&

Next

How do I always access my last yanked text regardless of deletes?