Valid phone numbers
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
987-123-4567123 456 7890(123) 456-7890(123)456-7890123-456-7890123-456-7890555-0100(555) 123-4567 ext 5Print, in this order:
- The valid numbers.
- The invalid lines, each with its line number.
- How many lines are valid.
- What an unanchored pattern would wrongly accept.
Expected output:
== valid numbers ==987-123-4567(123) 456-7890== invalid lines with their line numbers ==2:123 456 78904:(123)456-78905:123-456-7896:0123-456-78907:555-01008:(555) 123-4567 ext 5== how many are valid ==2== without anchors, a longer number sneaks in ==987-123-45670123-456-7890Hints
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.
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.
- The first command prints the two lines that match one of the shapes exactly.
-vnprints 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.-ccounts the valid lines and prints2.- 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.txtInterview 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\1demands the same character again, so987-123.4567is rejected. Backreferences ingrep -Eare 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.
grepreads 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 withzcat phones.txt.gz | grep -E '...'instead of unpacking it first. For several files, add-rto search a folder, or-Hto 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".