replace every instance of "xyz"
is really:
replace every instance of "xyz" on each line in the given range
and:
replace only first instance of "xyz"
is really:
replace only first instance of "xyz" on each line in the given range
Suppose this is the current line:
Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.
:s/dolor/XXX
will substitute only the first dolor
on the line with XXX
:
Lorem ipsum XXX sit amet. Lorem ipsum dolor sit amet.
^^^ 1st ^^^^^ 2nd, no substitution
:s/dolor/XXX/g
will substitute every dolor
on the line with XXX
:
Lorem ipsum XXX sit amet. Lorem ipsum XXX sit amet.
^^^ 1st ^^^ 2nd
Adding a range, so that the substitution is done on several lines, doesn't change the meaning of /g
.
:%s/dolor/XXX
will substitute only the first dolor
on each line of the given range with XXX
:
Lorem ipsum XXX sit amet. Lorem ipsum dolor sit amet.
Lorem ipsum XXX sit amet. Lorem ipsum dolor sit amet.
Lorem ipsum XXX sit amet. Lorem ipsum dolor sit amet.
Lorem ipsum XXX sit amet. Lorem ipsum dolor sit amet.
^^^ 1st ^^^^^ 2nd, no substitution
:%s/dolor/XXX/g
will substitute every dolor
on each line of the given range with XXX
:
Lorem ipsum XXX sit amet. Lorem ipsum XXX sit amet.
Lorem ipsum XXX sit amet. Lorem ipsum XXX sit amet.
Lorem ipsum XXX sit amet. Lorem ipsum XXX sit amet.
Lorem ipsum XXX sit amet. Lorem ipsum XXX sit amet.
^^^ 1st ^^^ 2nd
Which is probably what you imagine when you think "global". /g
is not "/g[lobal]
", it is just /g
.
But why do I go through all that hassle when :help :s_g
unambiguously says:
[g] Replace all occurrences in the line. Without this argument,
replacement occurs only for the first occurrence in each line. If
the 'edcompatible' option is on, Vim remembers this flag and toggles
it each time you use it, but resets it when you give a new search
pattern. If the 'gdefault' option is on, this flag is on by default
and the [g] argument switches it off.