How do I delete all lines that do NOT match a pattern?
Answer
:v/pattern/d
Explanation
The :v command (short for :vglobal) is the inverse of :g — it executes a command on every line that does not match the given pattern. Combined with d (delete), it becomes a powerful filter that keeps only the lines you care about.
How it works
:vselects lines that do NOT match the pattern/pattern/is any Vim regex patternddeletes those non-matching lines- The result is that only lines matching your pattern remain in the buffer
Example
Given a log file:
2024-01-15 INFO Starting server
2024-01-15 DEBUG Loading config
2024-01-15 ERROR Connection refused
2024-01-15 INFO Listening on port 8080
2024-01-15 ERROR Timeout expired
2024-01-15 DEBUG Cache miss
Running :v/ERROR/d leaves only:
2024-01-15 ERROR Connection refused
2024-01-15 ERROR Timeout expired
Tips
- Think of
:vas "inverse grep" — it's likegrep -vbut inside Vim - Combine with
:gfor surgical filtering::g/DEBUG/ddeletes matching lines,:v/ERROR/dkeeps only matching lines - Use
:v/pattern/don a visual selection by first selecting lines, then typing:which prefills:'<,'>, and appendingv/pattern/d - You can chain
:vwith other commands too, like:v/pattern/normal I#to comment out non-matching lines - Undo the whole operation with a single
usince:vgroups all deletes into one undo step