A better definition
The definition from earlier isn’t quite the full story. A better definition would be:
The global command lets you run an Ex command from each matching line in a range, defined by a regular expression.
The difference is subtle, but there are two key bits:
- the global command, contrary to its name, doesn’t have to act globally — you can give it a range, and it’ll only consider lines in that range
- the global command doesn’t run a command ‘against’ lines — it literally moves your cursor to the matching line, then runs the Ex command you gave it verbatim (this means that we can change lines around the matched lines by being clever with ranges)
How does it work?
The algorithm is quite simple:
- you give the global command a range, regular expression, and an Ex command
- the global command then finds all of the lines within your range that match your regular expression and marks them (first pass)
- for each marked line in order, the global command changes your current line to the marked line and executes your command verbatim (second pass)
This two-pass algorithm means that Vim won’t get confused about which lines to act on when, for example, adding and deleting lines with :global.
Try the global command again on the left. Notice how it leaves your cursor on the last regex match in the buffer! That’s because the global command is physically moving your cursor to each match.