Vim: Execute Commands On Global Matches And Their Surrounding Lines

Mike just schooled us with some “vim by example.” His use case:

I want to delete the line “Did not get valid lat and long”, the line before it, and the line after it, everywhere in this text file, from within vim.

Here’s how he did it:

:g/Did not get valid lat and long/-,/Did not get valid lat and long/+ d

How’s it work?

:g is the global command:

:[range]g/<pattern>/cmd

This executes a command on the specified range (defaults to whole file) for each line matching the pattern. It also supports this format:

:g/<pattern1>/,/<pattern2>/d

So, :g/<p1>/,/<p2>/d deletes inclusively from /<p1>/ to /<p2>/.

Additionally, /<p>/- and /<p>/+ mean “the line before and after the match”.

Put it all together and “voilà.” Thanks, Mike.

Stop wasting time on keystrokes and configuration. The Art of Vim will guide you along the path to Vim mastery through an ongoing series of Upcase screencasts with valuable tips and time savers.