Bash — Regular Expressions
Basic patterns
#!/bin/bash
# grep with basic regex
grep "pattern" file.txt
# grep with extended regex
grep -E "pattern1|pattern2" file.txt
# grep with fixed string
grep -F "literal" file.txt
Common patterns
#!/bin/bash
# Match email
grep -E "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$" file.txt
# Match IP address
grep -E "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$" file.txt
# Match phone number
grep -E "^\+?[0-9]{10,15}$" file.txt
Character classes
#!/bin/bash
# Any digit
grep -E "[0-9]+" file.txt
# Any letter
grep -E "[a-zA-Z]+" file.txt
# Any character
grep -E "." file.txt
# Word character
grep -E "\w+" file.txt
Quantifiers
#!/bin/bash
# Zero or more
grep -E "ab*" file.txt
# One or more
grep -E "ab+" file.txt
# Zero or one
grep -E "ab?" file.txt
# Exactly n
grep -E "ab{3}" file.txt
# Range
grep -E "ab{2,5}" file.txt
sed
#!/bin/bash
# Replace
sed 's/old/new/g' file.txt
# Delete lines
sed '/pattern/d' file.txt
# Insert
sed '3i\New line' file.txt
# In-place editing
sed -i 's/old/new/g' file.txt
awk
#!/bin/bash
# Print columns
awk '{print $1, $3}' file.txt
# Filter
awk '$3 > 100' file.txt
# Custom separator
awk -F',' '{print $1}' file.txt
# Sum column
awk '{sum += $2} END {print sum}' file.txt
Mini Practice
Write Bash code that:
- Uses
grepwith basic regex - Uses
sedfor text replacement - Uses
awkto extract columns - Matches an email pattern
Up Next
Congratulations! You've completed the Bash fundamentals. Continue exploring advanced topics like scripting patterns, cron jobs, and system administration.
Related Topics
Frequently Asked Questions about Regular Expressions
What is Regular Expressions in Bash?
Regular Expressions is a fundamental concept in Bash. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Regular Expressions?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Regular Expressions.
Why is Regular Expressions important in Bash?
Regular Expressions is essential for Bash development. Understanding this concept will help you write better code and solve real-world problems more effectively.