Vim, removing blank and commented lines in one regex

21,321

Solution 1

You can try this command:

:g/^\(#\|$\)/d

Or

:g/\v^(#|$)/d

  • $ matches literal '$' inside [...] (type :help /$ for help)
  • \| is for alternation
  • \v is very magic (minimal backslash escape)

Solution 2

Another way of solving this is keeping the non-commented lines:

:g!/^[^#]/d

Solution 3

You can combine regex patterns with the "or" operator: \|, eg:

:g/^\(#.*\|$\)/d

Though, in this particular case, you actually just need to specify that #.* is optional, eg:

:g/^\(#.*\)\?$/d

Finally, be aware that you can chain together most commands with VIM's (not regex's) "pipe" operator, also |, eg:

:g /^#/d | /^$/d

Solution 4

Try the following :

:g/^$/d | /^#/d

The | is there to combine multi command at the same time.

Solution 5

Expanding on kevs answer:
If anyone would also like to delete the comments in config files that are tabbed,
for example:

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    # SSL configuration
    #
    # listen 443 ssl default_server;
    # listen [::]:443 ssl default_server;
    #
    # Self signed certs generated by the ssl-cert package
    # Don't use them in a production server!
    #
    # include snippets/snakeoil.conf;
    ...

You can try this:

:g/\v^(#|$|\t#)/d
Share:
21,321
evfwcqcg
Author by

evfwcqcg

Updated on July 27, 2022

Comments

  • evfwcqcg
    evfwcqcg over 1 year

    I want to remove blank and commented lined at one time. I already found the similar question regarding removing blank lines, so for blank lines I use:

    :g/^$/d
    

    and for commented lines:

    :g/^#/d
    

    I'm curious is there any way to merge these regex in one? Something like

    :g/^[$#]/d
    

    but obviously it doesn't work in vim.

  • Will Palmer
    Will Palmer over 11 years
    you cannot pipe to g, but g applies across all commands in a pipeline. So this is better-written as :g /^$/d | /^#/d
  • Peter Perháč
    Peter Perháč almost 7 years
    only one thing I would suggest here is to send the deleted lines to the blackhole register by adding an underscore after the d operator. Like so: :g/\v^(#|$)/d_ This will be noticeably faster if the file is huge. Also the deleted comments are not likely needed for subsequent pastes so why keep them