O'Reilly logo

Linux Pocket Guide, 2nd Edition by Daniel J. Barrett

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Name

grep — stdin  stdout  - file  -- opt  --help  --version

Synopsis

grep [options] pattern [files]

The grep command is one of the most consistently useful and powerful in the Linux arsenal. Its premise is simple: given one or more files, print all lines in those files that match a particular regular expression pattern. For example, if a file contains these lines:

The quick brown fox jumped over the lazy dogs!
My very eager mother just served us nine pancakes.
Film at eleven.

and we search for all lines containing “pancake”, we get:

$ grep pancake myfile
My very eager mother just served us nine pancakes.

Now we use a regular expression to match lines ending in an exclamation point:

$ grep '\!$' myfile
The quick brown fox jumped over the lazy dogs!

grep can use two different types of regular expressions, which it calls basic and extended. They are equally powerful, just different, and you may prefer one over the other based on your experience with other grep implementations. The basic syntax is in Table 1-2.

Useful options

-v

Print only lines that do not match the regular expression.

-l

Print only the names of files that contain matching lines, not the lines themselves.

-L

Print only the names of files that do not contain matching lines.

-c

Print only a count of matching lines.

-n

In front of each line of matching output, print its original line number.

-b

In front of each line of matching output, print the byte offset of the line in the input file.

-i

Case-insensitive ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required