Search notes:

Vim command: g

:g/pattern/cmd
:range g/pattern/cmd
The g command first scans all lines in range and marks those that match pattern.
It then iterates over the marked lines and executes cmd. (See multi-repeat in vim's documentation).
If cmd happens to delete a marked line, the mark disappears.
Because of this two-pass operation, the g command, combined with the move command (m) allow to reverse the order of lines in a buffer:
:g/^/m0

Delete lines that match a pattern

Lines that match a pattern can be easily deleted with the global command combined with d:
:g/pattern/d

Yank lines that match a regular expressoin into a register

The following yanks lines that match a given regular expressions into the register c.
First make sure that the register is cleared:
qcq
Then, the g command is used like so:
:g/pattern/y B
Now, we have the matched lines in the register b.
This works because assigning to an uppercase register appends to the register with its lowercase name.

Extracting text from a buffer into a register

Here's a file:
some text
# xyz: one
more text
foo bar baz
# xyz: second
final text
# xyz: final words
The end.
I want to extract all text after # xyz:
I can do that with the global command:
:let @a='' | g/^# xyz:/let @A=substitute(getline('.'), '^# xyz: \(.*\)', '\1' . nr2char(10), '')
After executing this command, the register a contains
one
second
final words

Deleting every 2nd line

:g/^/+d
Note: this command throws error E16: invalid range if the number of lines in the buffer is odd.

See also

Ex commands

Index