TECH / Servers & Websites 2 min read

How to Strip Comments and Blank Lines from .conf Files in Linux

Antonio NEMCD Author
Published Mar 8, 2013 · 2 min

Reading massive default config files like squid.conf or php.ini can be exhausting: 90% of the file is inline documentation and commented examples, hiding the ten active lines you actually care about. One grep command cuts straight through the noise and shows only live directives.

Stripping comments from a Linux .conf configuration file

Always back up the original file before trimming it – those commented examples are priceless later when you want to check default parameter names.

Step 1. Back Up the Original Config

Using squid.conf as an example, keep a copy of the full original file first:

cp squid.conf squid.conf.orig

Step 2. Strip Comments (#) and Blank Lines with grep

Older cheat sheets often recommend egrep "^[^#]", which has two drawbacks: GNU grep 3.8+ deprecates egrep, and indented comments (lines with spaces before #) slip right through. The clean modern command handles both indentation and empty lines:

grep -Ev '^\s*(#|$)' squid.conf.orig > squid.conf

Here -E enables extended regex, -v inverts the match, and ^\s*(#|$) drops every line starting with # (even with leading spaces or tabs) as well as completely blank lines.

Handy Variations for Other Configs

  • Semicolon comments (php.ini, smb.conf): include both # and ; in the pattern:
grep -Ev '^\s*(#|;|$)' php.ini.orig > php.ini
  • Preview active settings without overwriting the file: simply omit the > redirect to inspect a live config cleanly in the terminal:
grep -Ev '^\s*(#|$)' /etc/ssh/sshd_config
  • Also strip inline trailing comments (sed): if your config has comments at the end of active lines (and no literal # symbols inside passwords or values), use sed:
sed -E 's/#.*$//; /^[[:space:]]*$/d' squid.conf.orig > squid.conf

A 2,000-line config shrinks down to 20–40 readable lines in half a second, while every original comment stays safely preserved in .orig.

Related posts:

Leave a Comment