Regular expressions (regex) allow powerful pattern matching in Bash. Theyβre used with tools like grep
, sed
, awk
, and even in Bash [[ ]]
conditionals.
A regular expression is a pattern that describes a set of strings. You can use it to:
Symbol | Meaning | Example |
---|---|---|
. |
Any single character | c.t β cat, cut |
* |
Zero or more of previous char | lo* β lo, loo, looo |
+ |
One or more | lo+ β loo, looo (not just βlβ) |
? |
Zero or one | lo? β l, lo |
^ |
Start of line | ^Hello |
$ |
End of line | done$ |
[] |
Character class | [aeiou] |
[^] |
Negated class | [^0-9] |
\ |
Escape special characters | \. matches literal . |
grep
grep "error" logfil
-E
):grep -E "^User: [A-Z][a-z]+$" users.txt
grep -i "warning" app.log
grep "[0-9]" input.txt
[[ =~ ]]
in BashBash supports regex matching inside [[ ]]
:
text="user_123"
if [[ $text =~ ^user_[0-9]+$ ]]; then
echo "Valid user ID"
fi
β οΈ Note:
[[ ... =~ REGEX ]]
([a-z]+)
if neededsed
#
:sed 's/[0-9]/#/g' file.txt
sed -E 's/ +/ /g' text.txt
awk
awk '/^user/ { print $0 }' users.txt
awk '$0 ~ /error/ { print $1 }' log.txt
Pattern | Matches |
---|---|
[A-Za-z0-9_]{3,8} |
Word with 3β8 alphanumerics |
^[a-z]+\@[a-z]+\.[a-z]+$ |
Basic email format |
[0-9]{3}-[0-9]{2}-[0-9]{4} |
SSN pattern (e.g. 123-45-6789) |
grep -E
for extended syntax[[ ]]
instead of [
when doing regex in Bashπ File:
advance/regex-patterns.md
Author: Kashif Alam