Tiny Code

Tiny Code

Sunday, January 27, 2013

Using grep in vim

One of the things I like about Vim (and vi) is the ability to invoke Unix utilities to manipulate text in ways that might be hard or impossible with just the regular editor commands.  It's definitely written with the Unix Philosophy in mind.

One thing I do frequently while debugging problems is to add log messages with a distinct pattern so I can find them easily in the log file.  For purposes of this example, let's assume the pattern I use is XYZ.  If I open the log file in Vim, I can issue the following command to isolate just the lines in the log file which contain XYZ.

^[ggVG!grep XYZ^M

That looks like a pretty complicated command, doesn't it?  But if we examine it piece by piece, it's not really that bad.

At the beginning of the command we've got ^[ which is the escape key.  Look at this ASCII chart if you're not familiar with the caret followed by a letter shorthand for control characters.  I issue the escape key to make sure Vim is in command mode.  While we're talking about control characters, the ^M at the end of the command is shorthand for the carriage return (AKA the Enter key).  That causes the command to be executed.

The ggVG in the command serves to do a visual selection of all the text in the file.  The gg causes the cursor to be placed at the first line of the file.  The V invokes visual marking of text.  And finally, the G causes the cursor to be placed on the final line of the file.  That causes the marked area to contain all the lines of the file.

The real meat of the command is the next part - !grep XYZ.  The exclamation mark pipes the marked text to the external Unix utility which follows which is the grep command.  This particular command line searches for lines which match a pattern of XYZ.

Issuing this command will cause Vim's current data buffer (the full contents of the log file) to be replaced with the output of the external Unix utility which will be just the lines within the log file which contain the pattern XYZ.

That makes it really simple to isolate just the log commands I've added.  Once I'm done, I can either exit Vim without saving or just issue the u command (undo last text manipulation) to leave the log file untouched.

No comments: