August 23, 2011

vim global command

The :global command is your friend - learn it well. It lets you run arbitrary :ex commands on every line that matches a regex. It abbreviates to :g.
To delete all lines that match "George Bush":
:g/George Bush/ d
The command that follows can have its own address/range prefix, which will be relative to the matched line. So to delete the 5th line after George Bush:
:g/George Bush/ .+5 d
To delete the DEBUG log entries:
:g/DEBUG/ .,+10 d
If you knew the stack trace was variable length but always ended at a blank line (or other regex):
:g/DEBUG/ .,/^$/ d
You can also execute a command on every line that does NOT match with :g!. e.g. to replace "Bush" with "Obama" on every line that does not contain the word "sucks":
 :g!/sucks/ s/Bush/Obama/
The default command is to print the line to the message window. e.g. to list every line marked TODO:
This is also useful for checking the regex matches the lines you expect before you do something destructive.
You can chain multiple commands using "|". e.g. to change Bush to Obama AND George to Barack on every line that does not contain "sucks":
 :g!/sucks/ s/Bush/Obama/g | s/George/Barack/g

1 comment:

  1. Thanks Tiebing,

    Excellent set of examples.
    Nice progression to more elaborate use cases.

    Also note that
    :g! (:global!) , is the same as
    :v (:vglobal).
    Memory association is that "grep -v" also outputs
    all lines that do not match the given pattern.

    I also found the ":exu" (:exusage) command to be
    a nice starting point for those unfamiliar with
    ":ex" commands.