Using GREP to Search a Server

While many search tools like “locate” search filenames, grep searching everything in the contents of files. This makes grep one of the most powerful tools for finding information on a Linux or Unix server. Grep (global regular expression print) can be used for both simple and complex searches. You can also use it as a filter for listed information.

Example 1: You want to find specific information in a document. You can use grep to search the document and print the information on the screen.

grep "business" /var/www/html/accounts/data.xml

This will find every instance of the word “business” in the XML file and print every line that contains it. If you expect a lot of results, you can forward the output to a file:

grep "business" /var/www/html/accounts/data.xml > data-results.txt

Example 2: You need to narrow down a list, essentially using grep as a filter. You want to find every file in the /usr/bin directory that contains the word “make”.

ls -al /usr/bin | grep make

The output will include cmake, makeconv, qmake, automake, and other similar commands.

Example 3: Grep works with just about any command that outputs text to the console. The ps command, which lists processes is another good example. If you want to know how many instances of Apache are running and do not want to have to scroll through a list to find it, use grep.

ps aux | grep httpd

Only lines that contain “httpd” will be displayed.

Grep is very powerful and can do much more than the three examples I have presented. You can view full grep documentation by typing “man grep” from the command line. You can also read this grep tutorial.