Both Ruby and Vim use "g" with substitution commands to mean "all occurrences." What does the "g" stand for?
Specifically, in Ruby, the String class has two "sub" commands: sub
will replace only the first occurrence, and gsub
will replace all occurrences. For example:
string = "One potato, two potato, three potato, four."
string.sub('potato','banana') # => "One banana, two potato, three potato, four."
string.gsub('potato','banana') # => "One banana, two banana, three banana, four."
Similarly, in Vim, :%s/foo/bar
will look through the whole file (which is what %
means) and substitute one occurrence per line, but :%s/foo/bar/g
will do all occurrences on each line.
My guess would be that in both cases, "g" means "greedy," because both the Ruby commands and the Vim command accept a regular expression, but my understanding of greedy matching is "match the longest possible substring meeting these criteria," not "match as many substrings as possible." (See "Watch Out for The Greediness!")
gsub (s, pattern, repl [, n]) Returns a copy of s in which all (or the first n , if given) occurrences of the pattern have been replaced by a replacement string specified by repl , which can be a string, a table, or a function. gsub also returns, as its second value, the total number of matches that occurred.
gsub! is a String class method in Ruby which is used to return a copy of the given string with all occurrences of pattern substituted for the second argument. If no substitutions were performed, then it will return nil. If no block and no replacement is given, an enumerator is returned instead.
Regular expressions (shortened to regex) are used to operate on patterns found in strings. They can find, replace, or remove certain parts of strings depending on what you tell them to do.
If I remember correctly it means global
, which this Wiki page seems to confirm:
The g flag means global – each occurrence in the line is changed, rather than just the first.
I think it stands for "global".
Following vim's help from :help :s
to :help s_flags
to :help gdefault
says:
'gdefault' 'gd' boolean (default off)
global
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With