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
:gis the global command — it executes an Ex command on all matching lines/pattern/is a regular expression to match against each linedis 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/ddeletes 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/donly affects lines 10-50