What Is grep?

Grep is a command-line tool that allows you to find a string in a file or stream. It can be used with a regular expression to be more flexible at finding strings.

This page gives an introduction to grep. For more information enter:

man grep

in a terminal.

How To Use grep

In the simplest case grep can be invoked as follows:

grep 'STRING' filename

The above command searches the file for STRING and lists the lines that contain a match.

This is OK but it does not show the true power of grep. The above command only looks at one file. A cool example of using grep with multiple files would be to find all lines in all files in a given directory that contain the name of a person. This can be easily accomplished as follows:

grep 'Nicolas Kassis' *

The above command searches all files in the current directory for the name and lists all lines that contain a match.

Notice the use of quotes in the above command. Quotes are not usually essential, but in this example they are essential because the name contains a space. Double quotes could also have been used in this example.

Regular Expressions

grep can search for complicated patterns to find what you need. Here is a list of some of the special characters used to create a regular expression:

^

Denotes the beginning of a line

$

Denotes the end of a line

.

Matches any single character

*

The preceding item in the regular expression will be matched zero or more times

[]

A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list; if the first character of the list is the caret ^ then it matches any character not in the list

\<

Denotes the beginning of a word

\>

Denotes the end of a word

Here is an example of a regular expression search:

grep "\<[A-Za-z].*\>" file

This regular expression matches any "word" that begins with a letter (upper or lower case). For example, "words" that begin with a digit would not match. The grep command lists the lines that contain a match.

More Information


CategoryCommandLine

grep (last edited 2016-07-03 08:44:03 by 81-178-228-156)