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

How do I delete all lines matching a pattern?

Answer

:g/pattern/d

Explanation

The :g/pattern/d command deletes every line in the file that matches the given pattern. This is Vim's global command combined with the delete action.

How it works

  • :g is the global command — it executes an Ex command on all matching lines
  • /pattern/ is a regular expression to match against each line
  • d is the delete command applied to each matched line

Example

Given the text:

apple
banana
apricot
cherry
avocado

Running :g/^a/d deletes all lines starting with a:

banana
cherry

Tips

  • Use :v/pattern/d (inverse) to delete all lines that do not match the pattern
  • The pattern supports full Vim regex: :g/TODO\|FIXME/d deletes all TODO and FIXME lines
  • You can use any Ex command instead of d: :g/pattern/normal A; appends a semicolon to matching lines
  • Combine with ranges: :10,50g/debug/d only affects lines 10-50

Next

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