A vim pattern search and delete example

vim FAQ: How do I perform a vim “search and delete” using a vim regular expression pattern (regex)?

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.

How to search and delete in vi/vim

Seeing that this is an election year ... assuming you have a file open in vim, and you want to delete all lines containing the string “George Bush”, you’d just enter this vim search and delete command:

:g/George Bush/d

That’s all you need to do. This vim search/delete command will find and then delete all lines containing the pattern “George Bush”.

How this vi search/delete command works

Here’s a brief explanation of how this vi/vim search and delete command works:

  • The : character says "put vim 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".

vim - delete all lines not matching a pattern

To delete all lines in a vim not matching a given pattern you can use one of these two commands:

:g!/foo/d

or this one:

:v/foo/d

Both of these commands delete all lines not contain the simple pattern “foo”.

Hopefully the first command is fairly easy to remember, as the ! operator is often used to negate the meaning of a command in many Unix tools and languages. I can probably remember the v command by thinking of the "grep -v" command, which reverses the meaning of a normal grep search.

vim search and delete with regex patterns

Now that you've seen that example, all you need to do to delete with a regular expression (regex) is to replace the vim search pattern shown above with your own regex pattern. For instance, a simple regex pattern for this same example is  "G.* Bush".

If you'd like more vim search/delete regex examples, just leave a note in the Comments section below and I'll be glad to work some up.