TIL: Vim - Deleting all lines that match a pattern

In Vim the :global command (or just :g) runs a command on every line that matches a pattern. Combined with :d (:delete) it becomes a quick way to remove lines in bulk.

The basics

Delete all lines that contain the word TODO:

:g/TODO/d

The format is :g/pattern/command. When the command is d, the line is deleted.

The inverse

The :v command (or :g!) does the opposite — it acts on the lines that do not match the pattern. For example, keep only the lines that contain error:

:v/error/d

Useful for filtering logs right in the buffer.

Useful examples

Delete blank lines:

:g/^$/d

Delete lines that start with # (comments):

:g/^#/d

Delete lines that contain console.log:

:g/console\.log/d

Restrict to a range (between lines 10 and 50):

:10,50g/TODO/d

Or using the visual marks after selecting in visual mode:

:'<,'>g/TODO/d