:g
, short for global
, executes a command on all lines that match a regex:
:g/LinesThatMatchThisRegex/ExecuteThisCommand
Example:
:g/hello/d
This will delete (d
) all lines that contain hello.
On the other hand, :%s
just performs a search (on a regex) and replace throughout the file:
:%s/hello/world/g
The g
at the end means global
or greedy
(this is disputed) so it will replace all occurrences on the line, not just one per line. You can also use the c
flag (:%s/hello/world/gc
) if you want to confirm each replacement manually.
This command replaces all occurrences of hello
with world
.
Both the :g
and :%s
commands support regular expressions.
The s
command means substitute
and the %
means throughout the buffer. So %s
means substitute throughout the entire buffer. You can also give a line range:
:10,15s/hello/world/g
This will execute the search and replace seen earlier on only lines 10 to 15 (inclusive).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…