O'Reilly logo

grep Pocket Reference by Agnieszka Klus, John Bambenek

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

Advanced Tips and Tricks with grep

As mentioned earlier, grep can be used in very powerful ways to search for content in files or across a filesystem. It is possible to use previous matches to search later strings (called backreferences). There are also a variety of tricks to search nonpublic personal information and even find binary strings in binary files. The following sections discuss some advanced tips and tricks.

Backreferences

The grep program has the ability to match based on multiple previous conditions. For instance, if you want to find all lines that repeatedly use a particular set of words, a single grep pattern will not work; however, it is possible to do this with the use of backreferences.

Suppose you wish to find any line that has multiple instances of the words “red”, “blue”, or “green”. Imagine the following text file:

The red dog fetches the green ball.
The green dog fetches the blue ball.
The blue dog fetches the blue ball.

Only the third line repeats the use of the same color. A regular expression pattern of ''(red|green|blue)*(red|green|blue)'' would return all three lines. To overcome this problem, you could use backreferences:

grep -E '(red|green|blue).*\1' filename

This command matches only the third line, as intended. For extended regular expressions, only a single digit can be used to specify a backreference (i.e., you can only refer back to the ninth backreference). Using Perl-style regular expressions, theoretically you can have many more (at least two digits). ...

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