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
.
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
qcq
Then, the g
command is used like so:
:g/pattern/y B
Now, we have the matched lines in the register b
.
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.