Remove lines matching pattern
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
We are sorry that this post was not useful for you!
Let us improve this post!
Tell us how we can improve this post?