The :global command

Vim · Advanced · 10 min

It turns 'delete every line containing X' or 'apply this macro to every matching line' into one command.

:[range]g/pattern/command marks every line matching the pattern, then runs the Ex command on each. The default range is the whole file and the default command is p (print).

  • :g/DEBUG/d deletes every line containing DEBUG.
  • :g!/pattern/d or :v/pattern/d deletes every line not matching, i.e. keeps only matches.
  • :g/^\s*$/d removes blank lines.
  • :g/TODO/t$ copies all TODO lines to the end of the file (t = copy, m = move).
  • :g/^/m0 reverses the file: each line is moved to the top in turn.

Combined with :normal, any Normal-mode keystrokes can be applied to the matching lines: :g/^def /normal A: appends a colon, and :g/pattern/normal @q runs a macro only where it is needed.

You can also nest a substitute to restrict it: :g/^SELECT/s/foo/bar/g replaces only on lines starting with SELECT. With an empty substitute pattern the inner :s reuses the global pattern: :g/old/s//new/g.

The whole :g operation is a single undoable change, so one u restores everything. Use :g/pattern/ (print) first to preview which lines are affected, or :g/pattern/# to show them with line numbers.

Example

:g/console\.log/d          " delete all console.log lines
:v/error/d                " keep only lines containing 'error'
:g/^\s*$/d                " delete blank lines
:g/TODO/#                 " list TODO lines with numbers
:g/^def /normal A  # noqa " append a comment to def lines
:g/^import/m0             " move imports to the top (reversed order)
:g/^SELECT/s/;$//         " strip ';' only on SELECT lines
:g/^/m0                   " reverse the whole file

Remember

  • :g/pat/cmd on matches, :v/pat/cmd on non-matches
  • Combine with d, m, t, s and normal
  • A whole :g run undoes with a single u

Watch out for

  • Running a destructive :g without previewing; :g/pat/ alone prints the lines first.

Check yourself

  1. What does `:v/foo/d` do?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: vimhelp.org/repeat.txt.html#%3Aglobal