Remove Lines Matching a Pattern in Vim

4.2
(236)

Yesterday, I was inspecting a log file in Vim. A substantial portion of the lines were unhelpful noise and I wanted to remove them. I could always use grep -v but there must be a way to do this using native Vim tools, right?

There is, of course! Using Vim’s powerful “global” command, :g for short. To remove lines matching a pattern, simply use the /d flag to the command. Here are some examples:

  • :g/pattern/d – Remove lines matching pattern
  • :g!/pattern/d – Remove lines that do NOT match the pattern
  • :v/pattern/d – Also removes lines that do not match the pattern

Here’s a quick gif of this in action. First, I use :g/userId/d to globally delete all the lines that contain “userId”. Then I undo, and use :g!/firstName/d to globally delete all the lines that do NOT contain “firstName”.

How useful was this tip?

Average rating 4.2 / 5. Vote count: 236

No votes so far! Be the first to rate this tip.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Written by

Colin Bartlett

105 Posts

Vim enthusiast and software developer for more than 20 years.
View all posts