-1

:%s/foo/bar/g

This vim command has saved me lots of time. But today I accidentally typed

:%s/foo/bar without the global (g) ending and it worked anyway! I was very confused. What's going on? Is it better to use the /g and why?

Nathan
  • 646
  • 1
  • 8
  • 25

2 Answers2

2

It does work even if you dont specify /g but it replaces only first occurrence of match and not the second and consecutive occurrences in the file.

  • 1
    It "works" but it does something different. If you only have one match on each line, the `/g` is superflouous, of course. – tripleee Feb 24 '18 at 18:29
  • 1
    Realized this was an impulsive question I could have looked up easily. Please close the question. If I can close it myself, I will do so – Nathan Feb 24 '18 at 18:33
2

%s/foo/bar/g runs s/foo/bar/g for each line. This replaces all instances of foo by bar.

%s/foo/bar runs s/foo/bar for each line. This replaces the first instance of foo by bar.

Suppose your file consists of

foo foo foo
foo foo foo
foo foo foo

Then %s/foo/bar/g turns it into

bar bar bar
bar bar bar
bar bar bar

But %s/foo/bar turns it into

bar foo foo
bar foo foo
bar foo foo