Skip to main content
Regular expressions (regex) let you define complex search patterns that go beyond simple grep queries. For instance, when you need to extract all IP addresses (e.g., 203.102.3.5) from hundreds of scattered files, a basic search for numbers and dots may yield invalid matches like 1.2. Regex allows you to impose precise conditions—just as you specify “x > 3” and “x < 8” in a math puzzle to limit x to 4, 5, 6, or 7.
The image shows a mathematical puzzle with conditions: "x is an integer," "x > 3," and "x < 8," with a sequence of numbers from 3 to 8 and question marks in between.
In the sections below, we’ll explore essential regex operators and examples using grep to filter and analyze text on Linux.

Core Regex Operators

The image displays a set of regex operators, including symbols like ^, $, ., *, +, {}, ?, |, [], (), and [^].
Below are practical grep examples—starting simple and building in complexity.

The Caret (^) – Match Beginning of Line

Given a file names.txt:
A plain search for sam returns any line containing that substring:
To match only lines that start with sam, anchor the pattern with ^:
The image shows a dark-themed terminal interface with a prompt and the text "The line begins with" above it. The word "KodeKloud" is visible in the top right corner.

The Dollar Sign ($) – Match End of Line

To find lines ending with a pattern, append $:
In system files like /etc/login.defs, search for lines containing the digit 7:
To list only those ending in 7:
And lines ending with mail:

The Dot (.) – Match Any Single Character

A dot (.) matches exactly one character. For example, c.t will match cat, cut, c1t, and even parts of longer strings:
To restrict matches to whole words, use the -w option:

Escaping Special Characters

To match a literal dot instead of using . as a wildcard, escape it with a backslash:

The Asterisk (*) – Zero or More Occurrences

The asterisk (*) applies to the preceding element, allowing zero or more matches. For instance, let* matches le, let, lett, letttt, etc.:
To match any path segment between slashes:

The Plus (+) – One or More Occurrences

The plus operator requires at least one occurrence of the preceding element.
Use \+ in basic grep to enable the plus operator, or switch to extended regex with grep -E.
If you omit the backslash (e.g., grep -r '0+' /etc/), + is treated literally, not as a quantifier.

Extended Regular Expressions

To avoid escaping metacharacters like +, use extended regex with grep -E or egrep:
With this foundation, you can harness regex patterns in Linux to perform precise text analysis and filtering.

References

Watch Video