21

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.

0

5 Answers 5

29

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)
1
  • 1
    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 Jul 9, 2017 at 22:44
5

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

:g!/^[^#]/d

4

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
3

Try the following :

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

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

1
  • you cannot pipe to g, but g applies across all commands in a pipeline. So this is better-written as :g /^$/d | /^#/d Sep 30, 2012 at 16:20
3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.