Skip to main content
Bash and Linux

Valid phone numbers

easygrep and regex

Problem statement

Print only the valid phone numbers from a file using grep -E with an anchored pattern. Checking that every line matches an exact format is a common job when you clean a contact export, validate a config field or check input before a script uses it, and it is a classic first regex task in shell interviews.

A phone number is valid in exactly two shapes: 123-456-7890 (three digits, a dash, three digits, a dash, four digits) or (123) 456-7890 (three digits in brackets, one space, then three digits, a dash and four digits). Anything else is invalid, including a valid number with extra text around it.

phones.txt

TEXT
987-123-4567
123 456 7890
(123) 456-7890
(123)456-7890
123-456-789
0123-456-7890
555-0100
(555) 123-4567 ext 5

Print, in this order:

  1. The valid numbers.
  2. The invalid lines, each with its line number.
  3. How many lines are valid.
  4. What an unanchored pattern would wrongly accept.

Expected output:

TEXT
== valid numbers ==
987-123-4567
(123) 456-7890
== invalid lines with their line numbers ==
2:123 456 7890
4:(123)456-7890
5:123-456-789
6:0123-456-7890
7:555-0100
8:(555) 123-4567 ext 5
== how many are valid ==
2
== without anchors, a longer number sneaks in ==
987-123-4567
0123-456-7890

Hints

Hint 1: grep -E turns on extended patterns, so {3} means "exactly three times" and | means "or". Digits are [0-9].

Approach

Optimal: grep -E with anchors

Covers: grep -E, [0-9], {n} counts, ( | ) alternation, escaping brackets with \( \), anchors ^ and $, and the flags -v, -n and -c.

Describe the whole line, not a piece of it. grep prints every line that contains a match. To accept only lines that are entirely a phone number, the pattern must say where the line starts and where it ends.

%%{init: {"flowchart": {"padding": 18, "nodeSpacing": 30, "rankSpacing": 40, "htmlLabels": true}, "themeVariables": {"fontSize": "18px"}}}%% flowchart TB S(["^ start of the line"]):::gray --> A{{"which shape?"}}:::blue A --> B["3 digits and a dash"]:::green A --> C["3 digits in brackets and a space"]:::green B --> M["3 digits, a dash, 4 digits"]:::purple C --> M M --> E(["$ end of the line"]):::gray classDef blue fill:#dbeafe,stroke:#2563eb,color:#1e3a8a,stroke-width:2px classDef yellow fill:#fef3c7,stroke:#d97706,color:#78350f,stroke-width:2px classDef green fill:#d1fae5,stroke:#059669,color:#064e3b,stroke-width:2px classDef red fill:#fee2e2,stroke:#dc2626,color:#7f1d1d,stroke-width:2px classDef purple fill:#ede9fe,stroke:#7c3aed,color:#4c1d95,stroke-width:2px classDef gray fill:#f3f4f6,stroke:#6b7280,color:#111827,stroke-width:2px linkStyle default stroke:#94a3b8,stroke-width:2px

The pattern is ^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$. Read it from left to right:

Part Means
^ the line starts here
[0-9]{3}- exactly three digits, then a dash
\([0-9]{3}\) an opening bracket, three digits, a closing bracket, then one space. The backslashes make the brackets plain characters
a pipe | inside round brackets "either this shape or that one". The two shapes sit inside one pair of round brackets
[0-9]{3}-[0-9]{4} three digits, a dash, four digits. Both shapes end this way
$ the line ends here

Why the brackets are escaped. In an extended pattern, a bare ( ) groups parts together. To match a real bracket character in the text, write \( and \).

The flags. -E enables extended patterns. -v flips the match, so only lines that do not match are printed. -n puts the line number in front of each line. -c prints only the number of matching lines instead of the lines.

Walking through the code. The # Setup: lines only create the sample file, so skip past them.

  1. The first command prints the two lines that match one of the shapes exactly.
  2. -vn prints everything else with line numbers. Line 6, 0123-456-7890, is rejected because it has an extra digit at the front. Line 8 is rejected because of the text after the number.
  3. -c counts the valid lines and prints 2.
  4. The last command drops the anchors on purpose. It accepts 0123-456-7890, which proves why ^ and $ are needed.

Edge cases. A blank line has no digits, so it is invalid and -v prints it. A trailing space makes a number invalid, because $ wants the line to end right after the last digit. Use [0-9] instead of \d, since \d does not work in grep -E.

# Setup: create the sample file in a fresh temporary folder
cd "$(mktemp -d)"
cat > phones.txt << 'DATA'
987-123-4567
123 456 7890
(123) 456-7890
(123)456-7890
123-456-789
0123-456-7890
555-0100
(555) 123-4567 ext 5
DATA

echo "== valid numbers =="
grep -E '^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$' phones.txt

echo "== invalid lines with their line numbers =="
grep -nvE '^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$' phones.txt

echo "== how many are valid =="
grep -cE '^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$' phones.txt

echo "== without anchors, a longer number sneaks in =="
grep -E '[0-9]{3}-[0-9]{3}-[0-9]{4}' phones.txt

Interview follow-ups

  • Also accept dots, like 987.123.4567, but never mix separators.

    Put the separator in a group and repeat it with a backreference: grep -E '^[0-9]{3}([-.])[0-9]{3}\1[0-9]{4}$' phones.txt. ([-.]) captures either a dash or a dot, and \1 demands the same character again, so 987-123.4567 is rejected. Backreferences in grep -E are a GNU feature, and they work on common Linux systems. If you only need to allow dots and do not care about mixing, [-.] in both places is enough and works everywhere.

  • The file has 50 million lines. Does anything change?

    No. grep reads the file one line at a time, so the memory use stays small however big the file is, and the same command works. If the file is gzipped, stream it with zcat phones.txt.gz | grep -E '...' instead of unpacking it first. For several files, add -r to search a folder, or -H to print the file name in front of each line.

Frequently asked questions

\d is a shortcut from Perl-style regular expressions, and plain grep -E does not know it. Write [0-9] or the portable class [[:digit:]] instead. GNU grep also has grep -P, which accepts \d, but -P is not available on every system, so -E with [0-9] is the safer habit in scripts and interviews.

They give the same result here. grep -x means "the whole line must match the pattern", which is the same as putting ^ at the start and $ at the end. Writing the anchors yourself is clearer when you read the pattern later, and it also works in tools that have no -x, such as sed and awk. Use whichever your team prefers, but do not leave both off.

Windows files end each line with a carriage return and a newline (\r\n). grep treats the \r as part of the line, so $ no longer sits right after the last digit and every number looks invalid. Strip the carriage returns first: tr -d '\r' < phones.txt | grep -E '...'. This is a very common cause of "my pattern works on my laptop but not on the file".