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

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

  • :v selects lines that do NOT match the pattern
  • /pattern/ is any Vim regex pattern
  • d deletes 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 :v as "inverse grep" — it's like grep -v but inside Vim
  • Combine with :g for surgical filtering: :g/DEBUG/d deletes matching lines, :v/ERROR/d keeps only matching lines
  • Use :v/pattern/d on a visual selection by first selecting lines, then typing : which prefills :'<,'>, and appending v/pattern/d
  • You can chain :v with other commands too, like :v/pattern/normal I# to comment out non-matching lines
  • Undo the whole operation with a single u since :v groups all deletes into one undo step

Next

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