In this post we will learn how to use grep command to remove commented lines. We can also use egrep command which is extended form of grep command.

As a Linux System Engineer, I mostly use some of the command. Most of the time when I am busy in playing on system, I generally meet with this requirement. That is reading long configuration file.

For an example, we want to read httpd.conf or php.ini file without commented lines. These are very long files and we only want to see what are the lines are not commented.

Commenting the lines different in various configuration files. In httpd.conf, we comment the file by putting hash(#) in front of line. Whereas in php.ini file, commenting the lines is done by using semicolon(;) in front of line.

So here is a simple logic. Remove the lines from display which starts with commented sign.Means in case of httpd.conf file, remove the lines start with hash(#) OR remove the commented lines in php.ini ,lines starting with semicolon(;).

Use the given below syntax:

grep -Ev '^comment-sign' /path/of/file

OR

egrep -v  '^comment-sign' /path/of/file

Example 1: In case of httpd.conf file where we use hash(#) for commenting ,use given below command

grep -Ev '^#' /etc/httpd/conf/httpd.conf

or

egrep -v '^#' /etc/httpd/conf/httpd.conf

You can also use remove blank lines along with removing commented lines. (Read our previous post on “grep command to remove blank lines from file“)

grep -Ev '^#|^$' /etc/httpd/conf/httpd.conf

or

egrep -v '^#|^$' /etc/httpd/conf/httpd.conf

Example 2: In case of php.ini file where we use semicolon(;) for commenting ,use given below command

grep -Ev '^;' /etc/php.ini

or

egrep -v '^;' /etc/php.ini

You can also use remove blank lines along with removing commented lines. (Read our previous post on “grep command to remove blank lines from file“)

grep -Ev '^;|^$' /etc/php.ini

or

egrep -v '^;|^$' /etc/php.ini

NOTE: If you see some file having some space in front of commented sign(special characters). Copy the space along with commented sign and use it in syntax.

example:

grep -Ev '^   #' /path/of/file

Read Some More Articles

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.