A little appreciation for Vim's 'g' command

February 2, 2019

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.)

Written on 02 February 2019.
« A bit of Sun's history that still lingers on in Illumos
My temptation of getting a personal laptop »

Page tools: View Source, Add Comment.
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Sat Feb 2 18:59:19 2019
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.