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

How do I run a command on every line that does NOT match a pattern?

Answer

:v/pattern/command

Explanation

:v (short for :vglobal) is the inverse of :g. It executes a command on every line that does not match the given pattern. It is equivalent to :g!/pattern/command. This is useful for deleting blank lines, filtering out noise, or operating on lines that lack a specific keyword.

How it works

  • :g/pattern/command — runs command on lines matching pattern
  • :v/pattern/command — runs command on lines not matching pattern

Both commands accept any Ex command as the action, including d (delete), s (substitute), norm (normal mode commands), yank, etc.

Example

Delete all lines that do not contain the word error:

:v/error/d

This leaves only lines containing error, effectively filtering a log file.

Delete all blank lines (lines matching only whitespace):

:v/\S/d

\S matches any non-whitespace character, so :v/\S/d deletes lines that contain no non-whitespace — i.e., blank or whitespace-only lines.

Tips

  • :g!/pattern/command is exactly the same as :v/pattern/command; use whichever reads more clearly.
  • Add a range to limit scope: :10,50v/TODO/d deletes lines without TODO only between lines 10 and 50.
  • Combine with :y to collect non-matching lines: :v/error/y A appends every non-error line to register a.

Next

How do I visually select a double-quoted string including the quotes themselves?