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

With awk:

awk '!/^ *#/ && NF' file
  • !/^ *#/ - means select lines which do not have space followed by # symbol
  • NF - means select lines which are not blank
  • && - is an and operator which ensure if both of the above are true then print the line.

This is probably easier with sed than grep:

sed -e '/^[[:space:]]*$/d' -e '/^[[:space:]]*#/d' test.in

Or with an ERE:

# Gnu sed need -re instead of -Ee
sed -Ee '/^[[:space:]]*(#|$)/d' test.in

With the ERE, grep can do it fairly easily too:

# Not sure if Gnu grep needs -E or -r
grep -vE '^\s*(#|$)' test.in

# or a BRE
grep -v '^\s*\(#\|$\)' test.in

With grep:

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

On OSX / BSD systems:

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