TExcelTAD
Home › Linux & Bash › Regular Expressions with grep -E

Regular Expressions with grep -E

A regular expression (regex) is a pattern that describes text: "a line starting with ERROR", "something that looks like an email address", "four digits, a dash, two digits". grep, sed, awk and Bash's [[ =~ ]] all understand them. This lesson uses grep -E (extended regular expressions), the most readable flavour.

Note: Regexes are not globs. In a glob * means "anything"; in a regex * means "the previous item, zero or more times" and "anything" is .*.

Literal text and the dot

bash · try it yourself
cat > words.txt <<'TXT'
cat
cart
coat
cut
c.t
TXT
grep -E 'c.t' words.txt | tr '\n' ' '; echo
grep -E 'c\.t' words.txt
grep -F 'c.t' words.txt
cat cut c.t
c.t
c.t

. matches any single character. To match a real dot, escape it as \. or use grep -F (fixed string, no regex at all).

Anchors

Anchor Matches
^ Start of line
$ End of line
\b Word boundary (GNU)
bash · try it yourself
cat > app.log <<'LOG'
ERROR disk full
WARNING: ERROR count rising
INFO ok
ERROR
LOG
grep -E '^ERROR' app.log
echo "---"
grep -E 'ERROR
  

 app.log
echo "---"
grep -Ec '^
  

 app.log
ERROR disk full
ERROR
---
ERROR
---
0

^$ matches empty lines (there are none here, so the count is 0).

Character classes

Class Matches
[abc] a, b or c
[a-z0-9] A lower-case letter or a digit
[^0-9] Anything except a digit
[[:digit:]], [[:alpha:]], [[:space:]], [[:upper:]] POSIX classes

Quantifiers

Quantifier Meaning
* 0 or more
+ 1 or more
? 0 or 1 (optional)
{3} Exactly 3
{2,4} 2 to 4
{2,} 2 or more
bash · try it yourself
cat > codes.txt <<'TXT'
SKU-1234
SKU-12
SKU-123456
sku-9999
ID 42
colour
color
TXT
grep -E '^SKU-[0-9]{4}
  

 codes.txt
echo "---"
grep -E '^SKU-[0-9]{2,4}
  

 codes.txt
echo "---"
grep -iE '^sku-[0-9]+
  

 codes.txt | wc -l
echo "---"
grep -E 'colou?r' codes.txt
SKU-1234
---
SKU-1234
SKU-12
---
4
---
colour
color

Groups and alternation

(...) groups part of a pattern, and | means "or":

bash · try it yourself
cat > requests.log <<'LOG'
GET /index.html 200
POST /api/login 401
GET /images/logo.png 200
DELETE /api/users/7 403
GET /docs/guide.pdf 404
LOG
grep -E '^(POST|DELETE) ' requests.log
echo "---"
grep -E '\.(png|jpg|gif) ' requests.log
echo "---"
grep -E ' 4[0-9]{2}
  

 requests.log | wc -l
POST /api/login 401
DELETE /api/users/7 403
---
GET /images/logo.png 200
---
3

Extracting matches with -o

grep -oE prints only the matched text, one match per line: the quickest way to pull values out of messy text.

bash · try it yourself
cat > contacts.txt <<'TXT'
Contact Ada at ada@example.com or ada.l@math.org.
Support: help@shop.example.com (24/7)
No address on this line.
Phone: +1-555-0100, alt +1-555-0199
TXT
grep -oE '[[:alnum:]._%+-]+@[[:alnum:].-]+\.[[:alpha:]]{2,}' contacts.txt
echo "---"
grep -oE '\+1-[0-9]{3}-[0-9]{4}' contacts.txt
ada@example.com
ada.l@math.org
help@shop.example.com
---
+1-555-0100
+1-555-0199

The email pattern is deliberately simple: real-world email validation is famously complicated. For extraction from logs, simple and readable patterns usually win.

Basic vs extended syntax

Plain grep (and sed without -E) uses basic regular expressions, where + ? | ( ) { } are literal characters unless escaped with a backslash:

Extended (grep -E, sed -E, awk) Basic (grep, sed)
a+ a\+
(ab)+ \(ab\)\+
x{2} x\{2\}
cat|dog cat|dog
bash · try it yourself
echo "aaa-bbb" | grep -o 'a\+'
echo "aaa-bbb" | grep -oE 'a+'
echo "a+b" | grep -o 'a+b'
aaa
aaa
a+b

Regex in Bash itself: [[ =~ ]]

Bash can match a regex without starting grep. Capture groups land in the BASH_REMATCH array. Store the pattern in a variable to avoid quoting problems:

bash · try it yourself
pattern='^([a-z]+)-([0-9]+)\.([0-9]+)\.([0-9]+)
  


for tag in app-1.4.2 web-10.0.1 broken_tag; do
  if [[ $tag =~ $pattern ]]; then
    echo "$tag -> name=${BASH_REMATCH[1]} major=${BASH_REMATCH[2]} minor=${BASH_REMATCH[3]}"
  else
    echo "$tag -> not a release tag"
  fi
done
app-1.4.2 -> name=app major=1 minor=4
web-10.0.1 -> name=web major=10 minor=0
broken_tag -> not a release tag

Tip: Write the pattern unquoted on the right of =~ (or in a variable, as here). Quoting it, as in [[ $x =~ "^a+" ]], makes Bash treat it as a literal string.

Test yourself

Which regex matches lines that start with #?

  1. #$
  2. ^#
  3. *#
  4. [#]$

With grep -E, what does ab+c match?

  1. ac only
  2. abc, abbc, abbbc …
  3. ab+c literally
  4. a, b or c

How do you match a literal dot in a regex?

  1. .
  2. \.
  3. [.]*
  4. *.