How to grep lines which does not begin with "#" or ";"?

grep "^[^#;]" smb.conf

The first ^ refers to the beginning of the line, so lines with comments starting after the first character will not be excluded. [^#;] means any character which is not # or ;.

In other words, it reports lines that start with any character other than # and ;. It's not the same as reporting the lines that don't start with # and ; (for which you'd use grep -v '^[#;]') in that it also excludes empty lines, but that's probably preferable in this case as I doubt you care about empty lines.

If you wanted to ignore leading blank characters, you could change it to:

grep '^[[:blank:]]*[^[:blank:]#;]' smb.conf

or

grep -vxE '[[:blank:]]*([#;].*)?' smb.conf

Or

awk '$1 ~ /^[^;#]/' smb.conf

Vim solution:

:v/^\s*[#\n]/p

I stumbled across this question when trying to find the vim solution myself.


These examples might be of use to people.

[user@host tmp]$ cat whitespacetest
# Line 1 is a comment with hash symbol as first char

# Line 2 is a comment with hash symbol as second char
  # Line 3 is a comment with hash symbol as third char
        # Line 4 is a comment with tab first, then hash
        ; Line 5 is a comment with tab first, then semicolon. Comment char is ;
; Line 6 is a comment with semicolon symbol as first char
[user@host tmp]$

The first grep example excludes lines beginning with any amount of whitespace followed by a hash symbol.

[user@host tmp]$ grep -v '^[[:space:]]*#' whitespacetest

        ; Line 5 is a comment with tab first, then semicolon. Comment char is ;
; Line 6 is a comment with semicolon symbol as first char
[user@host tmp]$

The second excludes lines beginning with any amount of whitespace followed by a hash symbol or semicolon.

[user@host tmp]$ grep -v '^[[:space:]]*[#;]' whitespacetest

[user@host tmp]$

Tags:

Grep