Search code examples
regexawksedgrep

How to print a file, excluding comments and blank lines, using grep/sed?


I'd like to print out a file containing a series of comments like:

    </Directory>
    ErrorLog ${APACHE_LOG_DIR}/error.log
    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn
    CustomLog ${APACHE_LOG_DIR}/ssl_access.log combined
    #   SSL Engine Switch:

In essence, the file contains multiple indentation levels, where a comment starts with a # symbol.

grep should remove blank lines, and also lines where there is a hash symbol before text (implying that these are comments).

I know that blank lines can be deleted via: grep -v '^$'

However how can I delete lines with leading whitespace, and then a # symbol, and print out only lines with actual code? I would like to do this in bash, using grep and/or sed.


Solution

  • With grep:

    grep -v '^\s*$\|^\s*\#' temp
    

    On OSX / BSD systems:

    grep -Ev '^\s*$|^\s*\#' temp