Grep Tutorial

Using the grep Command

Grep is one of the most useful commands. You can use grep on any UNIX-based operating system, and you can even get grep for Windows. When I'm stuck in Windows, I use use grep inside of Cygwin.

The syntax for grep is:

grep [options] PATTERN [FILE...]

Commonly used options are:

-e
This turns on extended regular expressions. It allows you to use regex patterns that aren't possible in regular grep. You can either turn this on by using grep -e or egrep — they are the same thing. See below for more about extended regular expressions.
-i
This makes the search case-insensitive.
-v
This means to find every line that doesn't match.
-o
This means to extract only the matching part of the line.
-m [number]
Stop after [number] of matching lines.
-r
Search recursively, decending into all subdirectories.
-n
Add line numbers to show where the match was in the file.

There are many more options than the common ones I've listed above. Type man grep in the terminal for a complete list.

Grep Example

To search a log file for every line that contains Googlebot and write to a file called google_access.log, you could use this:

grep Googlebot access.log > google_access.log

The following example of grep takes a logfile that only has hits from Googlebot and removes all of the requests for .png files.

grep -v \.png google_access.log > google_access_no_pngs.log
No votes yet
Syndicate content