grep is one of the most important text processing utilities that you will ever use. At some point you in your Linux system administration career you will need to touch grep tool. grep is powerful. You as a wannabe Linux administrator absolutely must to familiarize yourself with grep and regular expressions.

Let's start with the grep help command:

grep --help | less
# Usage: grep [OPTION]... PATTERN [FILE]...
Basic usage format of the grep command

You can see grep usage pattern. Not that scary. You start with grep command, followed by some options, followed by regex pattern and the file(s) you are filtering or processing.

On Linux, you will often see that configuration files contain a lot of comment lines explaining what you can do with the configuration file. If that is the case, it's not the comment lines that are interesting, it's everything that is not a comment line that is interesting.

For example, let's imagine we need to display to stdout all uncommented lines from /etc/ssh/sshd_config. Here is how to do it with grep.

grep -v '^#' /etc/ssh/sshd_config
Filtering lines that are not commented with grep

And here is the output of this command:





Port 22





PermitRootLogin no







ChallengeResponseAuthentication no



UsePAM yes

X11Forwarding no
PrintMotd no


AcceptEnv LANG LC_*

Subsystem	sftp	/usr/lib/openssh/sftp-server

We can see that this file contains a lot of empty lines and some SSH deamon directives that are not comment lines.

And here is the command to get rid of these empty lines:

grep -v -e '^#' -e '^$' /etc/ssh/sshd_config
Remove empty lines also

The output is something like this:

Port 22
PermitRootLogin no
ChallengeResponseAuthentication no
UsePAM yes
X11Forwarding no
PrintMotd no
AcceptEnv LANG LC_*
Subsystem	sftp	/usr/lib/openssh/sftp-server

Now there are no empty lines anymore.

There are a lot of useful options that you can use with grep. I will not go into details here, because you can find everything in man and help pages. If you want to actually remove comments from a file you can achieve that with sed stream editor in interactive mode.