Vim tip 23: editing lines filtered by a pattern
The syntax for g
command (short for global
) is shown below:
:[range]g[lobal]/{pattern}/[cmd]
This command is used to edit lines that are first filtered based on a searchpattern
.
- :g/call/d delete all lines containing
call
- similar to the
d
Normal mode command, the deleted contents will be saved to the default"
register - :g/call/d a in addition to the default register, the deleted content will also be stored in the
"a
register - :g/call/d _ deleted content won't be saved anywhere, since it uses the black hole register
- similar to the
- :g/^#/t0 copy all lines starting with
#
to the start of the file - :1,5 g/call/d delete all lines containing
call
only for the first five lines - :g/cat/ s/animal/mammal/g replace
animal
withmammal
only for the lines containingcat
- :.,.+20 g/^#/ normal >> indent the current line and the next
20
lines only if the line starts with#
- Note the use of
normal
when you need to use Normal mode commands on the filtered lines - Use
normal!
if you don't want user defined mappings to be considered
- Note the use of
You can use g!
or v
to act on lines not satisfying the filtering condition.
- :v/jump/d delete all lines not containing
jump
- same as :g!/jump/d
In addition to the /
delimiter, you can also use any single byte character other than alphabets, \
, "
or |
.
See :h :g for more details.
Video demo:
See also my Vim Reference Guide and curated list of resources for Vim.