|
Every once in a while when I'm using the vi editor (or vim) I find myself in a situation where I need to delete a bunch of lines in the file that match a particular pattern. In my younger days I used to get out of vi and then use sed or grep to get rid of those lines, but it turns out there's a real easy way to do this in vi.
Seeing that this is an election year ... assuming you have a file open in vi, and you want to delete all lines containing the string George Bush, you'd just enter this command:
:g/George Bush/d
That's all you need to do. Any lines containing the string "George Bush" will be deleted.
Here's a brief explanation of how that command works:
- The
: character says "put vi in last-line mode".
- The
g characters says "perform the following operation globally in this file".
- The forward slash characters enclose the pattern I'm trying to match. In this case it's a very simple sequence of characters, but it can also be a more complicated regular expression.
- The
d at the end of the command says "When you find this pattern, delete the line".
Of course you can also delete lines by searching with regular expression (regex) patterns, something like G.* Bush, for instance.
|