17

Sometimes my global substitutions don't substitute all matches in a line. It is confirmed by the fact that I can see it when I do substitutions with confirmation, a match is found in a line with multiple possible matches, but then it goes to another line.

I use the g or gc parameters operating on the entire file with %.

On this file:

hello hello
hello
hello hello hello
hello

If I do %s/hello/goodbye/g I get:

goodbye hello
goodbye
goodbye hello hello
goodbye

All I have in my .vimrc about search/replace is:

set hlsearch
set ignorecase
set incsearch
3
  • 4
    Please, give us a real world example and show us your vimrc.
    – romainl
    Commented Apr 16, 2016 at 14:50
  • 3
    What's the output of :echo &gd and what happens if you add a 2nd g flag like this: %s/hello/goodbye/gg or if you remove the g flag entirely? If the output of :echo &gd is 1, try adding set nogdefault at the end of your vimrc. Commented Apr 16, 2016 at 15:27
  • 2
    Fine! I don't know why but by default it was set to 0 so I added set nogdefault like you said and it works now, by the way. Thank you! Commented Apr 16, 2016 at 18:22

2 Answers 2

19

Maybe you, or a plugin, had enabled the option 'gdefault'. This option adds the flag g automatically whenever you perform a substitution.

So, when you manually add the flag g while 'gdefault' is enabled, it's as if you had 2 g flags which has the same effect as none. Therefore, Vim only substitutes the first occurrence of the pattern on every line.

By default, this option is disabled, but to make sure it is, you could add at the end of your vimrc: set nogdefault.

Alternatively, if you suspect a plugin might have enabled the option, you could track it down with: verb set gd?

Or you could get used to the option which means that when you want to substitute all the occurrences of a pattern, you don't add the g flag (because gdefault already did it), and when you want to only substitute the 1st occurrence of the pattern on a line, you add the g flag (because 2 g flags is the same as none).

-1

No need to change any settings. The syntax is wrong. You should use all %'s as shown below:

hello hello
hello
hello hello hello
hello

:%s%hello%goodbye%g

goodbye goodbye
goodbye
goodbye goodbye goodbye
goodbye

Usually you use / when doing specific line changes, e.g: something like:

:1,3 s/hello/goodbye/g

goodbye goodbye
goodbye
goodbye goodbye goodbye
hello
1
  • 2
    Welcome to Vi and Vim! Sorry, but this answer is incorrect, there's nothing wrong with the syntax using slashes and no reason why you would have to use %. Have you tried that yourself?
    – filbranden
    Commented Dec 1, 2020 at 15:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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