Catalog / GNU Grep Cheat Sheet
GNU Grep Cheat Sheet
A comprehensive cheat sheet for GNU grep, covering essential options, patterns, and usage examples for efficient text searching in files and streams.
Grep Basics and Usage
Basic Syntax
Searches for PATTERN in each FILE. If no files are specified, grep searches standard input. PATTERN can be a string or a regular expression. |
Example: |
|
|
Common Options
|
Ignore case distinctions in both the PATTERN and the input files. |
|
Select non-matching lines. |
|
Print only a count of matching lines per file. |
|
Prefix each line of output with the line number within its input file. |
|
Recursively search directories. |
|
Print only the names of files containing matches. |
Examples with Options
|
|
|
|
|
Regular Expressions in Grep
Basic Regular Expressions (BRE)
|
Matches the beginning of a line. Example: |
|
Matches the end of a line. Example: |
|
Matches any single character. Example: |
|
Matches zero or more occurrences of the preceding character. Example: |
|
Matches any single character within the brackets. Example: |
|
Matches any single character NOT within the brackets. Example: |
Extended Regular Expressions (ERE)
|
Matches one or more occurrences of the preceding character. Example: |
|
Matches zero or one occurrence of the preceding character. Example: |
|
Specifies an alternative. Example: |
|
Groups regular expressions. Example: |
|
Matches exactly n occurrences of the preceding character/group. Example: |
|
Matches between n and m occurrences of the preceding character/group. Example: |
ERE Examples
|
|
|
|
Advanced Grep Usage
Context Control
|
Print NUM lines of trailing context after matching lines. |
|
Print NUM lines of leading context before matching lines. |
|
Print NUM lines of output context. |
|
Use SEP as a group separator. The default is |
File and Directory Options
|
How to handle directories; ACTION can be read, skip, or recurse. |
|
Skip files matching GLOB. |
|
Search only files matching GLOB. |
|
Skip directories matching GLOB for recursive searches. |
Examples of Context and File Options
|
|
|
|
|
More Grep Pattern Options
Pattern Control Options
|
Use PATTERN as the pattern; useful to protect patterns beginning with |
|
Obtain PATTERN from FILE, one per line. |
|
Select only those lines containing matches that form whole words. |
|
Select only those matches that exactly match the whole line. |
Output Control Options
|
Stop reading a file after NUM matching lines. |
|
Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. |
|
Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. |
|
Surround the matching string with escape sequences to display it in color; WHEN is |
Pattern Option Examples
|
|
|
|
|
|