Delete all lines starting with # character

Tool used : VIM editor that comes with RHEL 7.4

I have a file like below. It has around 300 lines like below. All the lines starting with # are comments.
For readability, I removed all lines starting with # from vi (vim editor) using the command :g/^#/d . It seemed to have worked.
But, which is more accurate/safe :g/^#/d or :g/^ *#/d and why ? This is super-important configuration file. Hence I want to use the most accurate command.

$ cat config.properties 
#some comment1 
parameter1=blablah
#some more comment2
another parameter=blablah
#another comment3
parameter3=xyz

The second is the more reliable. If there is space before the # comment characters, it is still a comment. Even more reliable would be to remove possible TAB characters as well

1 Like

Thank You scrutinizer. :g/^ *#/d cannot take care of TABs.

ie. It cannot remove the line with #some comment1 shown below which has a TAB at the beginning. Any idea , how lines with TABs can also be dealt with ? Using vi or some other utility ?

$ cat config.properties2
    #some comment1 
parameter1=blablah
#some more comment2
another parameter=blablah
#another comment3
parameter3=xyz

Does your editor understand character classes? Try [[:space:]] in lieu of the single space...

If you are using Vim (as per your 1st post above), then Vim understands "\s" for whitespace. At least Vim versions 7 and higher.

Try:

:g/^\s*#/d

To check the version of your Vim editor, type on the shell prompt:

$ vim --version

or on the Vim prompt:

:version
1 Like

For regular vi you can enter a literal TAB character through CTRL-V TAB.
So:

:g/^[ ^I]*#/d

Where ^I denotes the TAB character entered through CTRL-V TAB

1 Like

Thank You Durden.

Where can I read more about "\s" ? What is this operator called ? (So that I can google about it )

I like this URL
The \s is in chapter "Perl Extensions".
In Linux the perl extensions sneak into the BRE and ERE, but they are not standard.
I would use them only in perl.

perl -ne '/^\s*#/ or print'

but not elsewhere

grep -v '^[[:space:]]*#'
sed '/^[[:space:]]*#/d'

Another one with awk

awk '$1!~/^#/'
2 Likes

It's a "metacharacter" or a "shorthand character class" in a regular expression.
Any book, blog or webpage on regular expressions should mention it.

Here's the Wikipedia page on regular expressions; search for "\s" on that page:
Regular expression - Wikipedia

Here's Jan Goyvaert's website on regular expressions in general. Pretty decent stuff.
Regexp Tutorial - Shorthand Character Classes

In particular, if you are looking for using regular expressions in the Vim editor, then this page looks pretty good:

Vim Regular Expressions 101

The books mentioned at the bottom of the above page are good too.
Jeffrey Friedl's book on regular expressions is the most advanced and a gold mine of information.

2 Likes