DEV Community

loading...

Vim Delete Line Vim - Delete Lines with Regex

Serhat Teker
Uomo Universale | Software Engineer | Entrepreneur | builds systems | py:js:go |
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
Enter fullscreen mode Exit fullscreen mode

Delete contains

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

:g/price/d
Enter fullscreen mode Exit fullscreen mode

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

:g/price\|customer\|secret/d
Enter fullscreen mode Exit fullscreen mode

Delete not contains

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

:g!/price/d
Enter fullscreen mode Exit fullscreen mode

~Some extras

Delete all empty lines

:g/^$/d
Enter fullscreen mode Exit fullscreen mode

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

:g/^\s*$/d
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Delete commented lines

:g/^<language comment string>/d
Enter fullscreen mode Exit fullscreen mode

E.g for python:

:g/^#/d
Enter fullscreen mode Exit fullscreen mode

All done!

Discussion (0)