Wandering Thoughts archives

2019-02-02

A little appreciation for Vim's 'g' command

Although I've used vim for what is now a long time now, I'm still somewhat of a lightweight user and there are vast oceans of useful vim (and vi) commands that I either don't know at all or don't really remember and use only rarely. A while back I wrote down some new motion commands that I wanted to remember, and now I have a new command that I want to remember and use more of. That is vim's g command (and with it, its less common cousin, v), or if you prefer, ':g'.

Put simply, g (and v) are filters; you apply them to a range of lines, and for lines that they match (or don't match), they then run whatever additional commands you want. For instance, my recent use of g was that I had a file that listed a bunch of checks to do to a bunch of machines, one per line, and I wanted to comment out all lines that referred to a test machine. With g, this is straightforward:

:g/cksvm3/ s/^/#/

(There's a whole list of additional things and tricks you can do with g here.)

Since I just tested this, it's valid to stack g and v commands together, so you can comment out all mentions of a machine except for one check with:

:g/cksvm3/ v/staying/ s/^/#/

This works because the commands run by g and v are basically passed the matching line numbers, so the v command is restricted to checking the line(s) that g matched.

There are probably clever uses of g and v in programming and in writing text, but I expect to mostly use them when editing configuration files, since configuration files are things where lines are often important in isolation instead of as part of a block.

Vim (and vi before it) inherited g and v from ed, where it appears even in V7 ed. However, at least vim has expanded them from V7 ed, because in V7 ed you can't stack g and v commands (a limitation which was carried forward to 4.x BSD's ed).

(Amusingly, what prompted me about the existence of g and v in Vim was writing my entry on the differences between various versions of ed. Since they were in ed, I was pretty sure they were also in Vim, and then recently I had a use for g and actually remembered it.)

unix/VimGCommandPraise written at 18:59:19; Add Comment

By day for February 2019: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15; before February.

Page tools: See As Normal.
Search:
Login: Password:
Atom Syndication: Recent Pages, Recent Comments.

This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.