Step 3 of 10

19. The Global Command

Useful Ex commands to use with the global command

Printing with the :print/:p command is the default action for the global command. If you don’t specify an Ex command, it’s assumed that you mean :print.

We can do a lot more than just print, though. Here are some useful Ex commands that you can use in conjunction with :global:

  • :delete/:d — used to delete a line — for example, :g/foo/d will delete all lines matching foo
  • :move/:m — can be used to move a line to a particular address — for example, :g/foo/m 0 will move all lines matching foo to the start of the file
  • :copy/:t — can be used to copy a line to a particular address — for example, :g/foo/t 0 will copy all lines matching foo to the start of the file
  • :norm ... — can be used to execute some normal mode commands on a line — for example, :g/foo/norm Abar will append bar to all lines matching foo

… plus many more.

Any Ex command can be used in conjunction with the global command, so feel free to use your imagination. In my experience, though, the ones listed above are the most useful.

Work through the checklist below. Delete all of the foo lines in one go, undo the damage, then use :move to herd the baz lines up to the top of the file.

  1. Delete every foo line with :g/foo/d Type :g/foo/d and hit Enter — all four foo lines will vanish in one command.
  2. Bring them back with u The whole :global run counts as a single change — press u, and one undo will restore all four lines.
  3. Move every baz line to the top with :g/baz/m 0 Type :g/baz/m 0 and hit Enter — the three baz lines will stack up at the start of the file.
Delete every foo line with :g/foo/d Type :g/foo/d and hit Enter — all four foo lines will vanish in one command.

Next: Bring them back with u

Loading editor…