0
0
Linux CLIscripting~5 mins

grep with regex (-E) in Linux CLI - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you want to find lines in text files that match complex patterns. The grep command with the -E flag lets you use extended regular expressions to search for these patterns easily.
When you want to find lines containing either 'cat' or 'dog' in a file.
When you need to search for lines starting with a number followed by a word.
When you want to find lines that contain either 'error' or 'warning' in logs.
When you want to match patterns with optional parts or repeated characters.
When you want to use simpler syntax for complex pattern matching compared to basic grep.
Commands
Create a file named animals.txt with three lines: cat, dog, and bird. This sets up the sample data for searching.
Terminal
echo -e "cat\ndog\nbird" > animals.txt
Expected OutputExpected
No output (command runs silently)
Search animals.txt for lines containing either 'cat' or 'dog' using extended regex with the -E flag.
Terminal
grep -E "cat|dog" animals.txt
Expected OutputExpected
cat dog
-E - Enables extended regular expressions for more powerful pattern matching.
Search numbers.txt for lines that start with one or more digits using extended regex. This example assumes numbers.txt exists with relevant content.
Terminal
grep -E "^[0-9]+" numbers.txt
Expected OutputExpected
No output (command runs silently)
-E - Use extended regex syntax.
Key Concept

If you remember nothing else from this pattern, remember: use grep -E to enable extended regular expressions for easier and more powerful text searching.

Common Mistakes
Using grep without -E and trying to use extended regex syntax like | or +.
Basic grep does not support extended regex, so the pattern will not work as expected.
Always add the -E flag when using extended regex features.
Forgetting to quote the regex pattern in the command.
The shell may interpret special characters in the pattern, causing errors or unexpected results.
Always put the regex pattern inside double quotes.
Summary
Use grep -E to search text files with extended regular expressions.
The -E flag allows using special regex symbols like |, +, and ? without escaping.
Always quote your regex pattern to avoid shell interpretation issues.