What is the global command?
Most explanations of what the global command does go something like this:
The global command lets you run a command against a set of lines defined by a regular expression
This is a good approximation, and will help us get started. In its most basic form, you can think of the global command as a tool for saying “run a command against all lines in the buffer matching a regular expression”.
With this in mind, here’s the syntax for basic use of the global command:
:global /regular_expression/ ex_command
:global here can be shortened to :g, and the whitespace outside of the regular expression is not significant. The following form is equivalent:
:g/regular_expression/ex_command
It’s worth noting that the ex_command at the end is optional; if you don’t specify it, it’ll default to :print/:p, which is used to print a line in the buffer.
Therefore, we can use something like :g/foo/p (or the shorter form :g/foo) to print all of the lines matching foo in the buffer.
Now the we understand the core concept of the global command, let’s try it out. In the editor, there is a message hidden among the HAYSTACK lines. The lines containing parts of the secret message always starts with the X character. Given this clue, try using the global command to print all of the lines starting with an X to uncover the hidden message!
If you’re really stuck, jump to the bottom of the file to see how it’s done.