Bash

πŸ” Regular Expressions in Bash

Regular expressions (regex) allow powerful pattern matching in Bash. They’re used with tools like grep, sed, awk, and even in Bash [[ ]] conditionals.


βœ… What Is a Regular Expression?

A regular expression is a pattern that describes a set of strings. You can use it to:


πŸ§ͺ Basic Regex Symbols

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 .

πŸ”Ž Using Regex with grep

Basic:

grep "error" logfil

Extended (-E):

grep -E "^User: [A-Z][a-z]+$" users.txt

Case-insensitive:

grep -i "warning" app.log

Match any digit:

grep "[0-9]" input.txt

🧰 Regex with [[ =~ ]] in Bash

Bash supports regex matching inside [[ ]]:

text="user_123"
if [[ $text =~ ^user_[0-9]+$ ]]; then
  echo "Valid user ID"
fi

⚠️ Note:


πŸ” Regex with sed

Replace all numbers with #:

sed 's/[0-9]/#/g' file.txt

Replace multiple spaces with one:

sed -E 's/ +/ /g' text.txt

πŸ“Š Regex with awk

Match lines starting with β€œuser”:

awk '/^user/ { print $0 }' users.txt

Use regex in condition:

awk '$0 ~ /error/ { print $1 }' log.txt

🧠 Advanced Patterns

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)

πŸ”’ Best Practices


πŸ“š References


πŸ“ File: advance/regex-patterns.md
Author: Kashif Alam