4

While working through vimtutor, I tried a variant on

:%s/old/new/g

by leaving off the g flag

:%s/old/new

and expected the substitution to only occur once in the whole file. After all, this mirrors the behavior of :s/old/new, which operates on the current line and only substitutes once unless the g flag is present.

However, the g the :%s substitution command does seem to matter, as both variants operate many times on the whole file. Is this documented anywhere, and how do you make sense of this discrepancy?


Workaround

I'm aware that I can replace just one instance anywhere in the file with

:%s/old/new/gc

and decline the prompt after the first substitution. I'm seeking understanding on the non-interactive version without the c flag.

6

The g flag to the :s command does not influence how many items are replaced in the whole file, but rather how often to apply the substition per line. E.g. :%s/foo/bar/g in a file like this:

foo foo foo
foo
foo

it will be replaced to

bar bar bar
bar
bar

while the command :%s/foo/bar/ will replace the file to:

bar foo foo
bar
bar

In general, if you want a region to be excluded from the effect of the :s command, you should use an address that excludes it from being affected by that command (this applies in general to all ex commands).

  • Thank you for the thorough explanation @Christian Brabandt :) – mxxk Apr 16 '18 at 21:11
  • 1
    @mksios And as always, the doc says it all: :h :s_flags – statox Apr 17 '18 at 7:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.