The Analogy: The Optical Comparator's Overlay Template
In a precision machine shop there is an instrument called an optical comparator. A finished part is placed in it and a bright lamp throws a hugely magnified silhouette of the part onto a frosted screen. Over that screen the inspector lays a transparent overlay chart: a sheet printed with the exact profile the part should have, plus tolerance bands drawn on either side. The inspector accepts the part only if its projected shadow follows the lines on the chart. That overlay chart is a regular expression -- a precise description of the shape a piece of text must have before grep will accept the line it sits on.
The chart has a small vocabulary of marks, and so does a regex. A solid line drawn on the overlay is a feature the part must have exactly, matching a literal character such as a or 7. A little window on the chart marked "any profile permitted here" is the wildcard ., which matches any single character. A band that lists several acceptable profiles -- accept a chamfer or a radius or a square edge -- is a character class [...], matching any one of the characters inside the brackets. And the registration marks that fix where the part must line up against the chart are the anchors ^ (the start of the line) and $ (the end).
Two things the chart must also express are repetition and which drafting standard it was drawn to. A feature annotated "may repeat" is a quantifier: * for zero or more, + for one or more, {n} for exactly n. Crucially, the shop uses two drafting standards. The older basic standard -- Basic Regular Expressions, what plain grep reads -- treats the symbols +, ?, {, (, and | as ordinary printed marks unless you annotate them with a backslash to promote them to control marks. The extended standard -- Extended Regular Expressions, what grep -E reads -- treats those same symbols as control marks by default. A chart read against the wrong standard misreads every one of those marks.
The failures at the comparator are failures of an imprecise chart. An overlay with too wide a wildcard window passes parts you meant to reject, which is over-matching -- a pattern that is too loose. Forget the registration marks and the chart will happily match a good sub-shape found anywhere inside a bad part, so a defective line slips through because a fragment of it fits: that is the difference between an unanchored and an anchored pattern. And mixing up the two standards -- drawing a + meaning "one or more" onto a chart that will be read as basic, where + is just a plus sign -- silently changes which parts pass. A regex, like an overlay chart, is only ever as good as its precision.
Syntax or Core Structure
A regular expression describes the shape of text; grep prints the lines whose text fits the shape. Here is a file contacts.txt of name age email records, and a single grep -E that accepts only well-formed lines.
# contacts.txt
Alice 34 alice@site.io
Bob 7 bob@mail.co
carol 128 carol@site.io
Dan 55 not-an-email
Eve 9 eve@site.io
grep -E '^[A-Z][a-z]+ [0-9]+ [a-z]+@[a-z.]+$' contacts.txt
Output:
Alice 34 alice@site.io
Bob 7 bob@mail.co
Eve 9 eve@site.io
Read the pattern as an overlay chart, left to right. ^ is the start-of-line registration mark. [A-Z][a-z]+ requires a capital letter followed by one or more lower-case letters -- a capitalised name. [0-9]+ requires a space, one or more digits, and a space. [a-z]+@[a-z.]+ requires a lower-case local part, an @, and a domain of lower-case letters and dots. $ is the end-of-line mark. The carol line fails at the very first mark (lower-case initial), and the Dan line fails because not-an-email has no @; both are rejected. The three well-formed lines pass.
Technical Depth: The Vocabulary of the Chart
Anchors and the two dialects
Anchors tie a pattern to a position rather than matching a character. ^ matches the start of the line and $ the end, so ^[A-Z] means "an upper-case letter at the very start".
grep '^[A-Z]' contacts.txt
Output:
Alice 34 alice@site.io
Bob 7 bob@mail.co
Dan 55 not-an-email
Eve 9 eve@site.io
The one lower-case line, carol, is dropped. The bigger decision is which dialect you are writing. In Basic Regular Expressions (plain grep) the operators below must be backslash-escaped to act as operators; in Extended Regular Expressions (grep -E) they are operators as written.
| Construct | BRE spelling | ERE spelling |
|---|---|---|
| one or more | a\+ | a+ |
| zero or one | a\? | a? |
| exactly n | a\{n\} | a{n} |
| grouping | \(ab\) | (ab) |
Alternation follows the same rule: it is \| in BRE and | in ERE. Because ERE spellings read the way most people expect, grep -E is the pragmatic default for anything beyond the simplest pattern; the characters ., *, [ ], ^, and $ are special in both dialects.
Character classes and POSIX names
A bracket expression [...] matches any one character it lists; [a-z] is a range, and a leading ^ inside the brackets negates it, so [^0-9] is "any non-digit". For readability and locale-safety, POSIX names such as [[:digit:]], [[:alpha:]], and [[:space:]] name whole classes. Combined with -o, which prints only the matched text rather than the whole line, a class extracts tokens:
grep -oE '[[:digit:]]+' contacts.txt
Output:
34
7
128
55
9
Each run of digits becomes its own output line, so -o turns grep into a simple field extractor.
Quantifiers and the escaped dot
A quantifier repeats the item before it: * (zero or more), + (one or more), ? (zero or one), and {n,m} (between n and m times). A subtle trap is the dot: unescaped, . matches any character, so to match a literal dot you must escape it as \.. This anchored pattern accepts only the site.io domain:
grep -E '@site\.io$' contacts.txt
Output:
Alice 34 alice@site.io
carol 128 carol@site.io
Eve 9 eve@site.io
Note that carol appears here though it failed the core validator: this pattern only checks the domain suffix, not the whole record. Had the dot been left unescaped as @site.io$, it would also match a nonsense domain like @sitexio, because . matches the x -- a common and quietly wrong shortcut.
Backreferences and whole words
A group (...) captures the text it matched, and a backreference \1 matches that same text again later in the pattern. This finds words containing a doubled character:
grep -E '(.)\1' words.txt
Output:
book
committee
balloon
(.) captures any character and \1 demands an immediate repeat of it, so oo, mm, tt, and ll all trigger a match while cat and desk do not. A different everyday need is matching a whole word rather than a fragment; the -w flag adds word boundaries around the pattern, so grep -w 'the' matches the standing alone but never the the inside theme.
Selecting whole lines: invert, count, and case
Regular expressions decide whether a line matches, but a handful of flags decide what grep does with that verdict. These four cover most day-to-day selection work:
| Flag | Effect |
|---|---|
-i | Ignore case when matching |
-v | Invert: print the lines that do not match |
-c | Print a count of matching lines instead of the lines |
-n | Prefix each printed match with its line number |
Inversion is the one people forget they need. To see every contact that is not on the site.io domain, invert the match rather than trying to write a pattern for "everything else":
grep -v 'site.io' contacts.txt
Output:
Bob 7 bob@mail.co
Dan 55 not-an-email
Case-insensitivity and line numbers combine cleanly. grep -in 'alice' finds the name regardless of capitalisation and tells you where it lives, printing 1:Alice 34 alice@site.io. Note that -v and -c compose too: grep -vc 'site.io' contacts.txt reports 2, the number of lines that survived the inversion, which is a quick way to answer "how many rows fail this filter" without eyeballing the list.
Real World Example: A SKU Format Auditor
A warehouse feed lists product SKUs that are supposed to follow one strict format: two upper-case letters, a hyphen, then exactly four digits, such as AB-1234. This audit_ids.sh reads the file, tags each SKU VALID or INVALID against an anchored ERE, and prints a summary count.
# skus.txt
AB-1234
xy-1234
AB-12
ZZ-9999
A1-2345
QT-4004
#!/usr/bin/env bash
# audit_ids.sh
set -euo pipefail
FILE="${1:-skus.txt}"
pattern='^[A-Z]{2}-[0-9]{4}$'
while IFS= read -r sku; do
if printf '%s\n' "$sku" | grep -qE "$pattern"; then
printf '%-10s %s\n' "$sku" "VALID"
else
printf '%-10s %s\n' "$sku" "INVALID"
fi
done < "$FILE"
valid=$(grep -cE "$pattern" "$FILE")
total=$(wc -l < "$FILE")
printf 'valid %d of %d\n' "$valid" "$total"
Running bash audit_ids.sh prints:
Output:
AB-1234 VALID
xy-1234 INVALID
AB-12 INVALID
ZZ-9999 VALID
A1-2345 INVALID
QT-4004 VALID
valid 3 of 6
The pattern ^[A-Z]{2}-[0-9]{4}$ is the whole story. ^ and $ anchor it to the entire line so a partial match cannot sneak through; [A-Z]{2} demands exactly two upper-case letters; - is a literal hyphen; and [0-9]{4} demands exactly four digits. xy-1234 fails on the lower-case letters, AB-12 fails because two digits is not four, and A1-2345 fails because 1 is not an upper-case letter. The three survivors are counted with grep -cE, which reports the number of matching lines without printing them.
Using grep -qE inside the loop keeps the per-line decision and the summary count on exactly the same pattern, so the listing and the tally can never drift apart in their definition of "valid". The -q flag makes grep silent and rely only on its exit status, which is why the if works cleanly. Anchoring is doing the heavy lifting: without ^ and $, the string ZZ-9999-EXTRA would match, because a valid SKU appears as a prefix inside it.
The code has a real design flaw that surfaces on messy input. The summary uses wc -l, which counts newline characters, while the listing loop uses while read, which does not execute its body for a final line that lacks a trailing newline, and grep -c, which does count that line. On a tidy file all three agree, but on a file whose last line has no trailing newline they diverge: the loop lists one fewer SKU than exist, grep -c and wc -l disagree by one, and the report can print the impossible line valid 2 of 1 -- more valid than total. A robust version would count with grep -c for both figures, or normalise the file to end with a newline before processing, rather than mixing three tools that treat the last line differently.
Common Mistakes
- Leaving a dot unescaped when you mean a literal dot. In
@site.iothe.matches any character, so it also accepts@sitexio. Escape it as\.to match a real dot, and remember a dot inside[...]is already literal.
- Using BRE syntax and wondering why
+and?do nothing. Plaingreptreats+,?,{,(, and|as ordinary characters. Either backslash them (a\+) or, far better, switch togrep -Ewhere they are operators.
- Forgetting to anchor a validation pattern. Without
^and$,grep -E '[0-9]{4}'matches any line that merely contains four digits, soZZ-9999-EXTRApasses as valid. Anchor whole-value checks at both ends.
- Assuming
grepmatches whole words.grep 'the'matchesthemeandothertoo. Use-wfor word boundaries, or write the boundaries into the pattern, when you mean a standalone word.
- Piping
grepoutput where the exit status was the point. Testingif grep ...should use-qsogrepstays silent and only its status matters; printing the match into a discarded pipe just clutters the output.
- Reaching for
\dand\win portable scripts. Those are PCRE shorthands available only withgrep -Pon GNU systems. For portability use POSIX classes such as[[:digit:]]and[[:alnum:]].
- Letting a quantifier attach to the wrong thing.
ab+repeats only theb, notab; to repeat the pair you must group it as(ab)+in ERE. Quantifiers bind to the single item immediately to their left.
- Depending on associative or unsorted output being ordered.
grepprints lines in file order, but any downstream grouping (for example piping into anawktally) should be sorted before you rely on the order of the result.
- Building a full CSV or email parser out of one regex. Real formats have quoting, escaping, and edge cases a single pattern cannot safely cover.
grepis excellent for selection and rough extraction; use a real parser when correctness on every input matters.
Best Practices
- Prefer
grep -Efor anything non-trivial. Extended syntax spells+,?,{n}, grouping, and alternation the way most people read them, so patterns are easier to get right and to review.
- Anchor patterns that validate a whole value. Wrap the pattern in
^and$so a valid fragment inside a larger string cannot pass as the whole thing.
- Escape every literal that is also a metacharacter. Dots, plus signs, and parentheses in your target text must be escaped (
\.,\+) so they match themselves rather than acting as operators.
- Use POSIX classes for portability. Write
[[:digit:]]and[[:space:]]rather than\dand\s, which depend ongrep -Pand are not available everywhere.
- Extract with
-oand test with-q.-oprints just the matched text for field extraction;-qgives a silent yes-or-no via exit status for use in conditionals.
- Keep one source of truth for a pattern. Store a validation regex in a variable and reuse it for both the per-item check and the count, so the two can never define validity differently.
- Build patterns incrementally against sample data. Start loose, run against a known file, and tighten until the output is exactly the set you expect before trusting the pattern in a script.
- Know when to stop using
grep. For quoted CSV, JSON, or anything with nested structure, switch to a parser built for the format instead of stretching a regular expression past its limits.
Practice Exercises
- Anchor an audit. Take
audit_ids.shand remove the^and$from the pattern. Feed it a line likeZZ-9999-EXTRAand show that it is now wrongly markedVALID, then restore the anchors and confirm it is rejected. Explain in one sentence what the anchors bought you.
- BRE versus ERE. Create a file containing the two lines
a+bandaaab. Rungrep 'a+'andgrep -E 'a+'against it and record which lines each prints. Write two sentences explaining why the results differ.
- Extract and tally. Given
contacts.txt, write a one-line pipeline that extracts every email domain (the text after@) withgrep -oE, then counts how many addresses use each domain, sorted. Verify the counts by eye.
- Fix the newline flaw. Reproduce the
valid 2 of 1bug by givingaudit_ids.sha file whose last line has no trailing newline. Then change the summary to derive both numbers fromgrep -cand show that the counts are now consistent. State whywc -lwas the wrong tool for the total.