Vim - Delete Lines with Regex
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!
Subscribe
Read Related