Linux Basic — Regular Expressions

1 minute read

Regular Expressions

Regular expressions (regex) are how you describe patterns in text. Every serious shell tool — grep, sed, awk, bash itself — speaks at least one regex dialect. This chapter teaches the dialect each tool actually accepts and the idioms that work.


What You Will Learn

By the end of this chapter you will be able to:

  • Tell BRE (basic) from ERE (extended) regex and pick the right flag
  • Use grep -E to filter text with extended patterns
  • Match a regex inside Bash with the [[ $str =~ re ]] operator and capture groups via BASH_REMATCH
  • Use POSIX character classes ([:alpha:], [:digit:], …) for portability
  • Apply regex with sed -E for substitution and awk for pattern actions

Topics in This Chapter

# Topic Description
1 grep -E in Scripts extended regex with grep
2 Bash =~ Operator regex inside [[ ]], BASH_REMATCH
3 POSIX Character Classes [:digit:], [:alpha:], etc.
4 sed Regex in Scripts substitution, anchors, capture refs
5 awk Regex Patterns pattern-action programs
6 Practice Exercises Hands-on tasks

BRE vs ERE in One Table

Construct BRE (grep, sed) ERE (grep -E, sed -E, awk, Bash =~)
Group \( \) ( )
Alternation not supported \|
One-or-more \+ (GNU ext.) +
Zero-or-one \? (GNU ext.) ?
{n,m} quantifier \{n,m\} {n,m}
. * ^ $ [ ] same in both same in both

Rule of thumb: when in doubt, use ERE (grep -E, sed -E). It’s what awk and Bash’s =~ use, so the same pattern works across all three.


A Tiny Pattern Vocabulary

Pattern Meaning
^abc line starts with abc
abc$ line ends with abc
. any single character
[abc] one of a, b, c
[^abc] not a, b, or c
\d not POSIX — use [0-9] or [[:digit:]]
a* zero-or-more a
a+ one-or-more a (ERE)
a? zero-or-one a (ERE)
a{2,4} 2 to 4 as (ERE)
(foo\|bar) foo or bar (ERE)

Next → grep -E in Scripts

Updated: