Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

grep

sed

awk

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.

like image 688
Joel G Mathew Avatar asked Jun 30 '13 17:06

Joel G Mathew


People also ask

How do I grep empty space in Linux?

If you want to only match space and tab, use [[:blank:]] or [ \t] .

How do I print 5 lines after grep?

You can use grep with -A n option to print N lines after matching lines. Using -B n option you can print N lines before matching lines. Using -C n option you can print N lines before and after matching lines.


1 Answers

With grep:

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

On OSX / BSD systems:

grep -Ev '^\s*$|^\s*\#' temp 
like image 62
gbrener Avatar answered Oct 13 '22 21:10

gbrener