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
Expression
Description
.
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
Expression
Description
*
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
Expression
Description
\d
Matches any digit
\D
Matches any non-digit
\s
Matches any whitespace character
\S
Matches any non-whitespace character
\w
Matches any word character (alphanumeric and underscore)
\W
Matches any non-word character
Anchors
Expression
Description
\b
Matches a word boundary
\B
Matches a non-word boundary
\<
Matches the beginning of a word
\>
Matches the end of a word
Lookarounds
Expression
Description
(?=...)
Positive lookahead
(?!...)
Negative lookahead
(?<=...)
Positive lookbehind
(?<!...)
Negative lookbehind
Examples
Expression
Description
grep 'hello' file.txt
Searches for the string ‘hello’ in file.txt
grep '^hello' file.txt
Searches for lines that start with ‘hello’ in file.txt
grep 'hello$' file.txt
Searches for lines that end with ‘hello’ in file.txt
grep '[aeiou]' file.txt
Searches for lines that contain any vowel in file.txt
grep '^[A-Z]' file.txt
Searches for lines that start with an uppercase letter in file.txt
grep '^[0-9]{3}' file.txt
Searches for lines that start with a three-digit number in file.txt
grep '\bthe\b' file.txt
Searches for the word ‘the’ in file.txt
grep '(?<=John )Doe' file.txt
Searches for the string ‘Doe’ preceded by ‘John ‘ in file.txt