:%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?
:%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?
 
    
    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.
 
    
    %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