0
0
Bash Scriptingscripting~5 mins

Extended regex (grep -E) in Bash Scripting

Choose your learning style9 modes available
Introduction
Extended regex lets you search text with more flexible patterns using grep -E. It helps find complex matches easily.
You want to find lines in a file that match multiple patterns at once.
You need to search for repeated characters or groups in text.
You want to use special symbols like +, ?, or | in your search.
You want to filter log files for specific error patterns.
You want to quickly check if a text contains one of several words.
Syntax
Bash Scripting
grep -E 'pattern' filename
Use single quotes around the pattern to avoid shell interpreting special characters.
The -E option enables extended regex features like +, ?, | without backslashes.
Examples
Find lines containing either 'cat' or 'dog' in pets.txt.
Bash Scripting
grep -E 'cat|dog' pets.txt
Find lines where 'a' appears one or more times followed by 'b'.
Bash Scripting
grep -E 'a+b' file.txt
Find lines with 'color' or 'colour' (the 'u' is optional).
Bash Scripting
grep -E 'colou?r' colors.txt
Sample Program
This script creates a file with animal names and searches for lines containing 'cat' or 'dog' using extended regex.
Bash Scripting
# Create a sample file
cat << EOF > animals.txt
cat
caterpillar
dog
doggy
cow
EOF

# Search for lines with 'cat' or 'dog'
grep -E 'cat|dog' animals.txt
OutputSuccess
Important Notes
Extended regex lets you write simpler patterns without many backslashes.
Remember to quote your pattern to protect special characters from the shell.
If you use basic grep without -E, some symbols need backslashes to work.
Summary
Use grep -E to enable extended regex for flexible text searching.
Patterns can include +, ?, | without extra backslashes.
Great for searching multiple options or repeated characters in files.