Grep Regex Cheat Sheet

Grep regex is a powerful tool used in Linux and Unix systems for searching and manipulating text. It stands for Global Regular Expression Print and is used to search for patterns in text files.

Regular expressions are a sequence of characters that define a search pattern. Grep regex uses these patterns to search for specific strings or patterns in a file. It can be used to search for a single word or a complex pattern of words, numbers, and symbols.

Grep regex is a command-line tool that can be used in conjunction with other commands to perform complex text manipulation tasks. It is commonly used in scripting and programming to automate tasks that involve searching and manipulating text files.

This cheat sheet provides an overview of the most commonly used regular expressions in grep.

Basic Regular Expressions

ExpressionDescription
.Matches any single character except newline
^Matches the beginning of a line
$Matches the end of a line
[]Matches any single character within the brackets
[^]Matches any single character not within the brackets
()Groups expressions together
|Matches either expression on either side of the pipe

Quantifiers

ExpressionDescription
*Matches zero or more occurrences of the preceding character
+Matches one or more occurrences of the preceding character
?Matches zero or one occurrence of the preceding character
{n}Matches exactly n occurrences of the preceding character
{n,}Matches n or more occurrences of the preceding character
{n,m}Matches between n and m occurrences of the preceding character

Character Classes

ExpressionDescription
\dMatches any digit
\DMatches any non-digit
\sMatches any whitespace character
\SMatches any non-whitespace character
\wMatches any word character (alphanumeric and underscore)
\WMatches any non-word character

Anchors

ExpressionDescription
\bMatches a word boundary
\BMatches a non-word boundary
\<Matches the beginning of a word
\>Matches the end of a word

Lookarounds

ExpressionDescription
(?=...)Positive lookahead
(?!...)Negative lookahead
(?<=...)Positive lookbehind
(?<!...)Negative lookbehind

Examples

ExpressionDescription
grep 'hello' file.txtSearches for the string ‘hello’ in file.txt
grep '^hello' file.txtSearches for lines that start with ‘hello’ in file.txt
grep 'hello$' file.txtSearches for lines that end with ‘hello’ in file.txt
grep '[aeiou]' file.txtSearches for lines that contain any vowel in file.txt
grep '^[A-Z]' file.txtSearches for lines that start with an uppercase letter in file.txt
grep '^[0-9]{3}' file.txtSearches for lines that start with a three-digit number in file.txt
grep '\bthe\b' file.txtSearches for the word ‘the’ in file.txt
grep '(?<=John )Doe' file.txtSearches for the string ‘Doe’ preceded by ‘John ‘ in file.txt

For more information on grep regular expressions, see the official documentation.