Introduction to UNIX for Web Developers The "grep" Utility The "grep" utility is used to locate a given word pattern within a file. Essentially, "grep" is a filter that accepts input from either the command line or a pipe and compares that input against a file. If the "grep" utility finds a match in the file, it prints out the line that matched. Consider the following example in which the pattern "mailto" is found in 6 HTML files...


The grep Utility is closely related to the "egrep" and "fgrep" utilities that we will not discuss here. The other two versions of "grep" have other capabilities but you will most likely never need them as a web technician. Of course, you can always check them out using the "man" utility as discussed on the first day of this tutorial.

As you might expect, grep accepts several useful options that are discussed in the table below:

Option Explanation
-b Prints the matching line with the block number
-c Displays the number of matching lines
-e pattern A special type of pattern match for when the pattern starts with a "-" character
-f filename Instructs grep to use the pattern defined in the given file.
-h Censors the file name from the display
-i Matches case insensitively.
-l Displays the list of filenames with matching content only (not the lines)
-n Displays the matching line numbers as well as the line
-s Censors error messages
-v Displays non-matching lines

Let's look at a few common examples of how to use grep.

Suppose you changed your email address and wanted to find all the web pages in a given directory that reference the old address so that you could modify them. In the following example, we search for and find two files we need to modify. Can you imagine how long it would take to search each file by hand!!!


[Spacer] Notice that in the above case, two files contained the old email address. But how do we know where in the file, the mailto reference is? Well we can easily get the line number using the -n option. In the following example we find that is found on the seventh line of edge.html. A quick use of the "head" utility proves the point.

[Grep and line numbers]

[Spacer] Now watch what happens when we check case insensitively! We find that there is actually another occurrence of the old email address, but it uses all capital letters instead of all lower case letters. It is often useful to use the -i option since UNIX is very fussy with capitalization

[Grep and case insensitivity]

[Spacer] Another useful way to use grep is to use the output from ls -l to review site permission settings. Consider these examples that search a directory for HTML files that have been set to be world editable and for directories.

[Grep and pipes]

Yet another useful application of grep is to look at your entry in the passwd file. For example, this is an easy way to find out what shell you are using.


Previous | Next | Table of Contents