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.txtcat 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