Remove comments and blank lines from a file

Want to make that httpd.conf look clean and tidy? Have a file that contains a lot of blank lines or comments that you don’t want? Here’s a quick trick to remove all the extra cruft.

Say I have a file called config.conf. This file looks like this:
-bash2.05b cswanson@helios ~ % cat config.conf
# Sample config file!

# Here is a sample comment. Note the blank lines.

$config=/etc/blah
echo $config $1

# Here is some more sample comments.

Now we run egrep on the file to remove the commented and blank lines:

-bash2.05b cswanson@helios ~ % egrep -v '^$|^#' config.conf
$config=/etc/blah
echo $config $1
-bash2.05b cswanson@helios ~ %

If you want to save this output to a file just use a simple redirect:

-bash2.05b cswanson@helios ~ % egrep -v '^$|^#' config.conf > config.conf-new
-bash2.05b cswanson@helios ~ % cat config.conf-new
$config=/etc/blah
echo $config $1
-bash2.05b cswanson@helios ~ %

UPDATE: If you’re using vi you can use the following commands to achieve the same thing.

Remove blank lines:
:g/^$/d

Remove commented lines:
:g/^\s*#/d

Of course there are other ways to skin this cat using sed/awk etc but the above two commands have proven to be quick and easy for me.

One Reply to “Remove comments and blank lines from a file”

Comments are closed.