The grep tool is a great text-searching tool. Using grep, you can search anything that is text, be it text in a file or text in a command’s output. Grep can search for simple strings or regular expressions, and it can present its output in a variety of useful ways.
For instance, to determine whether sshd is running, you would use:
$ ps ax | grep sshd
This pipes the output of ps ax as input to grep, which will in turn output any lines that match the string sshd. Of course, grep will pick up itself in this manner, so you can execute grep again to negate any occurrences of the string grep:
$ ps ax | grep sshd | grep -v grep
The -v option tells grep to invert the match, or only print out lines that don’t match.
If you only wanted a count of the number of lines matching, add the -c option:
$ ps ax | grep sshd | grep -v grep -c
This will tell you how many occurrences of sshd were found, which could be used in a script.
To have the matching strings highlighted in grep’s output, use the –color option. Grep will search through files as well, so pass it a wildcard or list of files, and it will search through those files. To search recursively, use the -R option:
# grep --color -R apache /etc/*
You can also add context to the output. For instance, to see one line of text before and another line after contained in the file where the match was found, use the -C option:
# grep --color -C 1 -R apache /etc/*
To recursively search for the string apache, but only print out files that match (not the matching strings themselves), use:
# grep -lR apache /etc/*
To use extended regular expressions, use the –E option or call egrep instead of grep:
# egrep -l -R '[Aa]pache$' /etc/*
The above would return a list of files that had lines ending with the word apache or Apache.
Grep is a fantastic tool and great for locating strings in text or other output. Once you get the hang of grep — and it’s quite easy to use — you will find yourself discovering even more ways to use it.
Delivered each Tuesday, TechRepublic’s free Linux NetNote provides tips, articles, and other resources to help you hone your Linux skills. Automatically sign up today!