loading...

Vim - Delete Lines with Regex

serhatteker profile image Serhat Teker Originally published at tech.serhatteker.com on ・1 min read

Global

The ex command :g -global command, is very useful for acting on lines that match a pattern.

Usually it works like this:

:[range]g/pattern/cmd

Delete contains

To delete all lines that contain "price" you can use:

:g/price/d

If you want to use multiple pattern you can use 'or' \|:

:g/price\|customer\|secret/d

Delete not contains

To delete lines that does NOT contain "price" you can use:

:g!/price/d

~Some extras

Delete all empty lines

:g/^$/d

Or deleting all lines that are empty or that contain only whitespace:

:g/^\s*$/d

Trim all whitespaces at the end of a line

Deletes any trailing whitespace at the end of each line. If no trailing
whitespace is found nothing changes, and the e flag means no error is
displayed. Since if nothings is found E486: Pattern not found error occurs.

:%s/\s\+$//e

Delete commented lines

:g/^<language comment string>/d

E.g for python:

:g/^#/d

All done!

Posted on by:

serhatteker profile

Serhat Teker

@serhatteker

Uomo Universale | Software Engineer | Entrepreneur | builds systems | py:js:go |

Discussion

markdown guide