Grep is a search utility that will look at each line of a file and check for matches against a given search pattern.

Grep command syntax

grep -i error logfile.txt

This command performs a case-insensitive search (-i) for the term “error” in the file “logfile.txt”. The output will include any line where the search term is found.

Output example:

Error 500, 10:05:12 Z, Internal server error
Error 404, 08:14:35 Z, Page could not be found
Success 200, 02:55:23 Z, No errors reported

Common Grep options

-i: Perform a case-insensitive grep search
-n: Display the line numbers
-v: Display only lines that DON’T match the pattern

--color: Append to the end of your grep command to color highlight the matched string in the output
--include: Append to the end of your Grep command to search only files that match a certain criteria (ex. “–include *.css” to only search .css files)

These are the most common options you’ll see used with Grep, but there are others.

Basic Grep examples

Search within multiple files using Grep

grep "error" logfile.txt syslog.txt

Show line numbers of matches

Use the -n option to have Grep show the line numbers where matches were found.

grep -n "error" logfile.txt

Search every file within a directory using Grep

Specify the -r (recursive) flag and a directory to Grep to search every file found within that directory.

grep -r "error" logs

Search every file within the current directory using Grep

Specify . instead of a directory name to indicate that Grep should search within the current directory.

grep -r "error" .

Search only files with a certain extension with Grep

To search only files with a certain file extension, utilize Grep’s --include flag. The following example will only Grep within .css files:

grep -r "flexbox" site --include \*.css

Write Grep results to a file

By default Grep will only print to standard output. To instead instruct Grep to print results to a file, use >:

grep -r 'Error' logs > error_logs.txt

Use Regular Expressions inside a Grep command

The Grep search pattern can include a variety of RegEx matchers. In this example, we are searching for lines that start with either “Error 401” or “Error 403”:

grep "^Error 40[4,3]" logfile.txt

Want more info about RegEx with Grep? Try this article.