How to Use grep with Regex in Linux: Syntax and Examples
Use
grep with regex by running grep 'pattern' filename, where pattern is your regular expression. For extended regex features, add the -E option like grep -E 'pattern' filename.Syntax
The basic syntax for using grep with regex is:
grep 'pattern' filename: Searches forpatternusing basic regular expressions in the file.grep -E 'pattern' filename: Uses extended regular expressions for more complex patterns.grep -i: Makes the search case-insensitive.grep -r: Recursively searches directories.
bash
grep 'regex_pattern' filename grep -E 'extended_regex_pattern' filename
Example
This example shows how to find lines containing words that start with 'cat' followed by any characters in a file named animals.txt.
bash
echo -e "cat\ncaterpillar\ndog\ncatalog\nbird" > animals.txt grep '^cat' animals.txt
Output
cat
caterpillar
catalog
Common Pitfalls
Common mistakes include:
- Not quoting the regex pattern, which can cause shell interpretation errors.
- Using basic regex when extended regex is needed for special characters like
+or?. - Forgetting to escape special characters in basic regex mode.
Example of wrong and right usage:
bash
grep 'cat+' filename # Wrong: '+' is treated literally in basic regex grep -E 'cat+' filename # Right: '+' means one or more 't's
Quick Reference
| Option | Description |
|---|---|
| -E | Use extended regular expressions |
| -i | Ignore case distinctions |
| -r | Search recursively in directories |
| -v | Invert match (show lines that do NOT match) |
| -n | Show line numbers with output |
Key Takeaways
Always quote your regex pattern to avoid shell errors.
Use
-E option for extended regex features like +, ?, |.Test your regex on sample data to ensure it matches as expected.
Remember
grep is case-sensitive by default; use -i to ignore case.Use recursive
-r to search through directories.