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

How do I run a command on every line matching a pattern?

Answer

:g/pattern/command

Explanation

The :g/pattern/command (global) command executes an Ex command on every line in the file that matches the given pattern. It is one of Vim's most powerful features, enabling complex batch edits with a single command.

How it works

  • :g is the global command
  • /pattern/ is a regular expression to match lines against
  • command is any Ex command to execute on each matching line

Vim scans the entire file, marks every line that matches the pattern, and then executes the command on each marked line in order.

Examples

Delete all lines containing "debug":

:g/debug/d

Yank all lines containing "TODO" into register a:

:g/TODO/yank A

Indent all lines containing "return":

:g/return/>

Move all lines containing "import" to the top of the file:

:g/import/m 0

The inverse: :v (vglobal)

Use :v/pattern/command to execute a command on every line that does not match the pattern. For example, delete all lines that do not contain "keep":

:v/keep/d

Tips

  • Use :g/pattern/normal @a to run a macro on every matching line
  • Use :g/^$/d to delete all blank lines in a file
  • Use :g/pattern/s/old/new/g to run a substitution only on lines matching a pattern
  • The global command supports ranges: :10,50g/pattern/d operates only on lines 10–50
  • Use :g/pattern/p to print all matching lines without modifying anything (like a built-in grep)
  • Chain with :normal to run normal-mode commands: :g/TODO/normal I// comments out all TODO lines
  • The pattern uses Vim's regex syntax — use \v for "very magic" mode if you prefer Perl-like regex

Next

How do I edit multiple lines at once using multiple cursors in Vim?