Use sed to remove commented and blank lines

This is especially useful for config files. Say you have a file like:

1
2
3
4
5
cats = True
# cats = False

cat_names = ["Plop","Fluffy"]
#

Let’s say your desired output is:

1
2
cats = True
cat_names = ["Plop","Fluffy"]

If this awesome stuff if all in a file called cats.cfg, you would run a command like:

1
sed  's/#.*$//;/^$/d'  cats.cfg

Add in -i to make the changes in line in cats.cfg.

1
sed -i 's/#.*$//;/^$/d'  cats.cfg

Example

1
2
3
4
5
6
7
8
9
10
$ cat cats.cfg
cats = True
# cats = False

cat_names = ["Plop","Fluffy"]
#
$ sed 's/#.*$//;/^$/d' cats.cfg
cats = True
cat_names = ["Plop","Fluffy"]
$