Frequently Asked Question
What does the g flag do in :substitute, and how does the % range work?
Vim's substitute command is :s/pattern/replacement/flags. With no flags,
it replaces only the first match on the current line. The g flag
("global within the line") tells it to replace every match on the line.
So :s/foo/bar/ changes one foo on this line; :s/foo/bar/g changes all
foos on this line.
A range in front of :s chooses which lines to operate on. With no
range, just the current line. :5,10s/foo/bar/g covers lines 5 through
10. :.,$s/foo/bar/g covers the current line to the end of file. The
shorthand % means "every line in the file": :%s/foo/bar/g is the
standard "replace all foo with bar everywhere" command. Add the c flag
(:%s/foo/bar/gc) and Vim stops on each match and asks for confirmation
(y, n, a for all remaining, q to quit).
Two other flags matter often: i forces case-insensitive matching for
this command (overriding the ignorecase setting), and e suppresses
the "Pattern not found" error if there are no matches, useful when
scripting. The pattern is a regular expression in Vim's own dialect, and
the replacement supports back-references (\1, \2) and special items
like \u (uppercase the next character) and & (the whole match).