You are previewing grep Pocket Reference.

grep Pocket Reference

Cover of grep Pocket Reference by John Bambenek... Published by O'Reilly Media, Inc.
O'Reilly logo

grep Basics

There are two ways to employ grep. The first examines files as follows:

grep regexp filename

grep searches for the designated regexp in the given file (filename). The second method of employing grep is when it examines “standard input.” For example:

cat filename | grep regexp

In this case, the cat command will display the contents of a file. The output of this command is “piped” into the grep command, which will then display only those lines that contain the given regexp. The two commands just shown have identical results because the cat command simply passes the file unchanged, but the second form is valuable for “grepping” other commands that alter their input.

When grep is called without a filename argument and without being passed any input, it will let you type in text and will repeat it once it gets a line that contains the regexp. To exit, press Ctrl-D.

At times, the output is remarkably large and hard to scroll through in a terminal. This is usually the case with large files that tend to have repetitious phrases, such as an error log. In these cases, piping the output to the more or less commands will “paginate” it so that only one screen of text is shown at a time:

grep regexp filename | more

Another option to make the output easier to look at is to redirect the results into a new file and then open the output file in a text editor at a later time:

grep regexp filename > newfilename

Also, it may be advantageous to look for lines that contain several patterns instead of ...

The best content for your career. Discover unlimited learning on demand for around $1/day.