Originally published by Robert Beisert at fortcollinsprogram.robert-beisert.com

Linux + C – grep

Let’s revisit filters with a timeless classic – grep.

grep – the search tool

One of the most common filters we employ is the mighty grep (global regular expression print). This tool searches for a regular expression (read: normal text) within files, allowing us to find which files contain the content we’re looking for. It’s much like the “search” tools on websites or within word processing programs.

The basic search contains three paramaters, in the following order:

grep “REGULAR EXPRESSION” file1 file2 …

That means that we can search for the text “REGULAR EXPRESSION” within any number of files using the grep tool.

We can replace the file names with asterisks (*) to check all files in the current directory.

grep “Regular Expression” *

We can also use grep recursively (that is, go through subdirectories in addition to the current directory) using the -R option with no file names.

grep -R “Regular Expression”

Regular expressions are a powerful tool which very few understand. This tutorial at gnosis.cx is an excellent breakdown of the topic – I highly recommend it. I will also be covering this content in the near future, but for now go to the link.

Example

The following series of images demonstrate most of the common uses of grep. I didn’t include grep -R, because there aren’t interesting results in our subdirectories. You can play with grep -R as an exercise.

2015-09-23-211603_1920x1080_scrot
Basic grep: We check all the files in our directory for the word “Hello”
Searching for "Hello," in a specific set of files
Searching for “Hello,” in a specific set of files
The -l argument only prints the name of the file, not the whole matching line
The -l argument only prints the name of the file, not the whole matching line
The -i argument ignores case. Notice the difference between the matching responses with and without the -i flag.
The -i argument ignores case. Notice the difference between the matching responses with and without the -i flag.
The -c flag prints how many lines match within the file.
The -c flag prints how many lines match within the file.
The -x flag searches for an EXACT match. It looks for a line that contains the exact content of the Regular Expression (and finds none, in our case). For comparison, we search the same string with -i.
The -x flag searches for an EXACT match. It looks for a line that contains the exact content of the Regular Expression (and finds none, in our case).
For comparison, we search the same string with -i.

Note: In the future, we will refer to Regular Expressions as Regex (Pronounced with the hard g in “guard”, not the soft g in “giant”). This is the community abbreviation.

photo by: