Real-World Regex Patterns
Practical Regex Applications in Shell Scripting
Regex patterns solve complex text processing challenges in real-world shell scripting scenarios, enabling efficient data validation, extraction, and transformation.
Common Validation Patterns
Pattern Type |
Regex Example |
Use Case |
Email |
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ |
Validate email addresses |
Phone Number |
^\+?[1-9][0-9]{7,14}$ |
Validate international phone numbers |
IP Address |
^(\d{1,3}\.){3}\d{1,3}$ |
Validate IPv4 addresses |
#!/bin/bash
log_file="/var/log/system.log"
## Extract critical error messages
critical_errors=$(grep -E 'ERROR|CRITICAL' "$log_file" | awk '{print $5,$6,$7}')
## Validate and process IP addresses
valid_ips=$(grep -oE '([0-9]{1,3}\.){3}[0-9]{1,3}' "$log_file" | sort -u)
Pattern Matching Workflow
graph TD
A[Input Data] --> B{Regex Pattern}
B -->|Matches| C[Extract/Validate]
B -->|No Match| D[Discard/Handle]
C --> E[Process/Transform]
Advanced Pattern Techniques
## Complex pattern for log parsing
parse_log() {
local log_entry="$1"
if [[ $log_entry =~ ^([0-9]{4}-[0-9]{2}-[0-9]{2}).*\[(WARN|ERROR)\]:(.*)$ ]]; then
echo "Date: ${BASH_REMATCH[1]}"
echo "Level: ${BASH_REMATCH[2]}"
echo "Message: ${BASH_REMATCH[3]}"
fi
}
Regex patterns transform shell scripts into powerful text processing tools, enabling sophisticated data manipulation with concise, readable code.