today I started to use vim. I get confused at :g
and :%s
commands. So, what is the difference between :g
or :%s
commands?
: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).
-
1
:g
executes only on the current buffer, in the same way of:s
. They only difference is in the default range::s
is the same as:.s
while:g
is:%g
. Therefore:%s/pat/subs
and:%g/pat/ cmd
(or:g/...
) will act on all lines on the buffer that matches the pat, and:.s/pat/subs
(or:s/...
) and:.g/pat/ cmd
will act on the current line if it matches pat. – mMontu Sep 5 '14 at 12:45 -
2The
g
at the end (//g) is more likely short forgreedy
as used in general regex lingo, including in the original PCRE API. It basically means "consume as many of the matches as possible". Tried editing it in but no luck, so a comment it is. – miyalys Apr 20 '18 at 22:51
They are different.
:g
can execute commands for matched lines. :s
is one of those commands. That is you can combine :g and s
:%s
just do search and replace on whole buffer, even though it can do some other things with expression too, but it is not as straightforward as :g
.
E.g.:
:g/foo/s/bar/blah/g
this will do bar->blah
substitution on lines which contain foo
. With :s
we could:
:%s/foo/\=substitute(getline('.'), 'bar','blah','g')
so :g
is easier.
So if you are dealing with substitution task, usually :s
should come up first. If you want to do something like for all lines that matches xxx, I want to delete/join/indent/....... :g
maybe helpful for you.
:%s
is a substitute command applied to the whole document, not a global common prefix as:g
. – Jean-Karim Bockstael Sep 5 '14 at 11:16:g[lobal]
command with theg:[name]
prefix for options and variables. – Ingo Karkat Sep 5 '14 at 11:35:help tutor
. – mMontu Sep 5 '14 at 12:55:help
there are lots of information. Section|usr_10.txt| Making big changes
has further explanation on:s
and:g
commands. – mMontu Sep 5 '14 at 13:03