The grep command searches text files for specific patterns. Combine it with regular expressions to create powerful search capabilities. This tool helps system administrators find configuration errors and developers locate code patterns.
This guide shows how to use grep with regex through practical examples.
Prerequisites
- Access to a Linux terminal
- A text file for practice (examples use
/etc/passwd) - Basic understanding of grep command syntax
Grep Regex Syntax
The grep command accepts regular expressions in this format:
grep [options] 'pattern' filename
Regular expressions contain two character types:
Literals match exact text. Metacharacters have special meanings unless escaped with a backslash.
Grep supports three regex types. Basic Regular Expression (BRE) is the default. Extended Regular Expression (ERE) requires the -E flag. Perl Compatible Regular Expression (PCRE) needs the -P flag.
Basic Grep Regex Example
Search for the word “bash” in the passwd file:
grep 'bash' /etc/passwd
The command displays lines containing “bash”. Results include “bash”, “bashrc”, and any word with the character sequence b-a-s-h.
Searches are case-sensitive by default. Add -i to match both uppercase and lowercase:
grep -i 'bash' /etc/passwd
Using Grep Regex Patterns
Master these fundamental patterns to build complex searches.
Literal String Matching
Literal patterns match exact character sequences. Search for “root” in the passwd file:
grep 'root' /etc/passwd
This finds lines with the exact sequence r-o-o-t in order.
For multi-word searches, use quotes:
grep 'system user' /etc/passwd
Anchor Patterns
Anchors define where matches occur in a line. The caret ^ matches line beginnings. The dollar sign $ matches line endings.
Find lines starting with “root”:
grep '^root' /etc/passwd
Find lines ending with “bash”:
grep 'bash$' /etc/passwd
Combine both anchors to match complete lines:
grep '^root:.*bash$' /etc/passwd
Locate empty lines using only anchors:
grep '^$' /etc/passwd
Wildcard Character Matching
The period . matches any single character at that position.
Search for three-letter words starting with “b” and ending with “t”:
grep 'b.t' /etc/passwd
This matches “bat”, “bit”, “but”, and any character between b and t.
Use multiple periods for longer patterns:
grep 'r..t' /etc/passwd
This matches “root”, “rest”, “r12t”, or any four characters starting with r and ending with t.
Bracket Expressions
Brackets create character sets for a single position. The pattern matches if any character in the set appears.
Match lines with “cat” or “cut”:
grep 'c[au]t' /etc/passwd
Use the caret inside brackets to exclude characters:
grep '[^0-9]' /etc/passwd
This matches lines containing non-numeric characters.
Define ranges with hyphens:
grep '[a-z]' /etc/passwd
This finds lowercase letters.
Combine multiple ranges:
grep '[^a-zA-Z0-9]' /etc/passwd
This matches special characters and symbols.
Character Classes
Character classes simplify common bracket expressions. These predefined sets improve pattern readability.
| Class | Description | Equivalent |
|---|---|---|
[[:alnum:]] |
Letters and numbers | [a-zA-Z0-9] |
[[:alpha:]] |
Letters only | [a-zA-Z] |
[[:digit:]] |
Numbers only | [0-9] |
[[:lower:]] |
Lowercase letters | [a-z] |
[[:upper:]] |
Uppercase letters | [A-Z] |
[[:space:]] |
Whitespace characters | Spaces and tabs |
Find lines containing digits:
grep '[[:digit:]]' /etc/passwd
Repetition Quantifiers
Quantifiers specify how many times a pattern appears.
| Quantifier | Meaning |
|---|---|
* |
Zero or more occurrences |
? |
Zero or one occurrence |
+ |
One or more occurrences |
{n} |
Exactly n occurrences |
{n,m} |
Between n and m occurrences |
The asterisk matches zero or more repetitions:
grep 'ro*t' /etc/passwd
This matches “rt”, “rot”, “root”, and “rooot”.
Use extended regex for plus and question mark:
grep -E 'ro+t' /etc/passwd
This requires at least one “o” between r and t.
Find three-digit numbers:
grep -E '[0-9]{3}' /etc/passwd
Match phone numbers with flexible formatting:
grep -E '[0-9]{3,4}' /etc/passwd
Alternation Operator
The pipe symbol creates OR conditions between patterns.
Search for “error” or “warning” in log files:
grep -E 'error|warning' /var/log/syslog
Combine multiple alternatives:
grep -E 'fatal|error|critical' /var/log/syslog
This matches lines containing any of the three terms.
-E flag. Without it, escape the pipe character as \|.
Pattern Grouping
Parentheses group patterns into single units. Apply quantifiers to entire groups.
Match “bash” or “bashrc”:
grep -E 'bash(rc)?' /etc/passwd
The question mark makes “rc” optional.
Combine grouping with alternation:
grep -E '(error|fail)ed' /var/log/syslog
This matches “errored” or “failed”.
Word Boundary Matching
Special sequences match word edges and boundaries.
| Expression | Description |
|---|---|
\b |
Word boundary |
\< |
Word start |
\> |
Word end |
\w |
Word character |
\W |
Non-word character |
Find the word “set” without matching “reset” or “setup”:
grep '\bset\b' /etc/passwd
Match words starting with “user”:
grep '\<user' /etc/passwd
Escaping Special Characters
Escape metacharacters with backslashes to search for literal symbols.
Find lines ending with a period:
grep '\.$' /etc/passwd
Search for literal asterisks:
grep '\*' /etc/passwd
Match IP addresses:
grep -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' /etc/hosts
Conclusion
Grep regex enables precise text searches across files and command outputs. Start with simple literal matches and anchors. Progress to bracket expressions and quantifiers. Combine these elements to create sophisticated search patterns.
Practice these techniques regularly. Complex searches become intuitive with experience.
FAQs
Grep always uses regex patterns. Basic grep uses simple literal matches. Extended regex with -E enables advanced pattern matching including quantifiers and alternation.
Use the caret anchor followed by your pattern: grep '^text' filename. This matches lines beginning with “text” only.
Use grep -E when patterns require plus signs, question marks, parentheses, or pipes. Extended regex eliminates the need to escape these special characters.
Yes. Specify multiple files or use wildcards: grep 'pattern' file1 file2 or grep 'pattern' *.txt. Add -r for recursive directory searches.
Add the -i flag: grep -i 'pattern' filename. This matches uppercase, lowercase, and mixed-case variations of the pattern.