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— runscommandon lines matchingpattern:v/pattern/command— runscommandon lines not matchingpattern
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/commandis exactly the same as:v/pattern/command; use whichever reads more clearly.- Add a range to limit scope:
:10,50v/TODO/ddeletes lines withoutTODOonly between lines 10 and 50. - Combine with
:yto collect non-matching lines::v/error/y Aappends every non-error line to registera.