Step 1 of 10

19. The Global Command

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 that 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 start with the X character — so a pattern of ^X will find every one of them, and the default :print action will show them all at once. When you put the output away, notice where your cursor has landed — a later step explains why it moves. And if you get stuck, the very bottom of the buffer holds the solution.

  1. Reveal the hidden message with :g/^X Type :g/^X and hit Enter — every X line will print. Hit Enter again to put the output away.
Reveal the hidden message with :g/^X Type :g/^X and hit Enter — every X line will print. Hit Enter again to put the output away.

Last one — goal check runs when it's done

Loading editor…