VimTrick: Remove lines matching pattern
Skip grep and use Vim's built-in method of filtering lines
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”
.
Was this useful? Help us improve!
With your feedback, we can improve VimTricks. Click a link to vote: