Vim `:g` and :`v`
If you want to execute a command on all lines matching a pattern, you
can use the Ex command :g
. For example, if you want to delete all
blank lines, you can do
:g/^\s*$/d
It will get all lines that matches this: from the beginning (^
), it may
contain 0 or more whitespace (\s*
) until the end of line ($
). In other
words, if the line is empty or contain only whitespace.
For all lines matching that criterium, delete it (d
).
You can also execute commands on all lines not matching the pattern.
Instead of g
, use v
:
:v/^[a-z]\+:/d
That will delete all lines not starting with a lowercase word followed by a colon.
Imagine this file:
title: Vim search
tags: ["vim", "regex"]
date: 2024-11-04
Some text.
More text.
All lines, except the first three, will be removed.
Photo by the author