Regex Patterns
BRE basics — escaped grouping and quantifiers
# BRE requires \( \) for grouping and \{n,m\} for quantifiers
echo 'abc123def456' | sed 's/\([a-z]\{3\}\)\([0-9]\{3\}\)/[\1]-[\2]/g'
ERE with -E — unescaped grouping, +, ?, alternation
# ERE: ( ) grouping, {n,m} quantifiers, + and ? all unescaped
echo 'abc123def456' | sed -E 's/([a-z]{3})([0-9]{3})/[\1]-[\2]/g'
Character classes — [:digit:], [:alpha:], [:space:]
cat <<'EOF' > /tmp/charclass.txt
User: admin Port: 443
User: guest Port: 80
Error 404: not found
EOF
# [:digit:] matches any digit; [:alpha:] any letter
sed -E 's/[[:digit:]]+/[NUM]/g' /tmp/charclass.txt
Anchors — ^, $, and GNU word boundaries
cat <<'EOF' > /tmp/anchors.txt
leading space
trailing space
the cat concatenated
EOF
# ^ matches start, $ matches end
echo 'hello world' | sed 's/^hello/HELLO/'
echo 'hello world' | sed 's/world$/WORLD/'
# \b word boundary (GNU sed) — matches "cat" but not inside "concatenated"
sed 's/\bcat\b/DOG/g' /tmp/anchors.txt
Backreferences — \1 through \9, swap fields
cat <<'EOF' > /tmp/backref.txt
2026-04-11
2025-12-25
2024-01-01
EOF
# Swap date from YYYY-MM-DD to DD/MM/YYYY using 3 capture groups
sed -E 's/([0-9]{4})-([0-9]{2})-([0-9]{2})/\3\/\2\/\1/' /tmp/backref.txt
Negated character class — match everything except
# [^...] matches any character NOT in the set
echo 'abc123!@#def' | sed 's/[^a-zA-Z]//g'
Alternation with ERE — match multiple patterns
cat <<'EOF' > /tmp/altern.txt
status: active
status: disabled
status: pending
status: active
EOF
# (foo|bar) alternation requires ERE (-E flag)
sed -E 's/(active|pending)/ENABLED/' /tmp/altern.txt
Match and extract IP addresses
cat <<'EOF' > /tmp/ips.txt
server 10.50.1.20 is running
gateway at 192.168.1.1 responds
dns 10.50.1.50 resolves
nothing here
EOF
# Extract IP addresses — print only lines with IPs, strip surrounding text
sed -n -E 's/.*([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}).*/\1/p' /tmp/ips.txt
Match and normalize MAC addresses
cat <<'EOF' > /tmp/macs.txt
iface eth0: 14:f6:d8:7b:31:80
iface wlan0: 98-BB-1E-1F-A7-13
iface eth1: 00:11:22:33:44:55
EOF
# Normalize dash-separated MACs to colon-separated, lowercase
sed -E 's/([0-9A-Fa-f]{2})-/\1:/g' /tmp/macs.txt | sed 's/.*/\L&/'
Match and reformat dates
cat <<'EOF' > /tmp/dates.txt
Created: 04/11/2026
Updated: 12/25/2025
Archived: 01/01/2024
EOF
# Reformat MM/DD/YYYY to YYYY-MM-DD
sed -E 's|([0-9]{2})/([0-9]{2})/([0-9]{4})|\3-\1-\2|' /tmp/dates.txt