Eric Leung Code and Data Learnings     about     blog     projects     misc     feed

Delete lines with a pattern in vim

In vim, I know you can search and replace text with :s/FINDTHIS/REPLACE/g to replace all occurrences in a line after pressing Ctrl-v.

But then, I recently wanted to delete all lines containing a certain pattern and wondered if vim could do this. Turns out. It can.

Below is the pattern to delete lines with a certain pattern.

:g/searchterm/d

The /d indicates we’re deleting lines and leading g stands for “global” in order to affect the entire buffer.

The use case I wanted was to delete lines that started with the number zero. We can also use these commands1 to do more complex search and delete.

:g/^0/d

You can read more here or by pressing :help :g (global changes) and :help :d (delete lines).

  1. Apparently, these are called Ex commands. Maybe I’ll cover these in another post.