Valid Phone Numbers - Problem

Given a text file file.txt that contains a list of phone numbers (one per line), write a one-liner bash script to print all valid phone numbers.

You may assume that a valid phone number must appear in one of the following two formats:

  • (xxx) xxx-xxxx
  • xxx-xxx-xxxx

where x means a digit. You may also assume each line in the text file must not contain leading or trailing white spaces.

Input & Output

Example 1 — Mixed Format File
$ Input: file.txt contains: (555) 123-4567 555-123-4567 555.123.4567 5551234567
Output: (555) 123-4567 555-123-4567
💡 Note: Only the first two lines match valid formats: (xxx) xxx-xxxx and xxx-xxx-xxxx
Example 2 — All Valid Numbers
$ Input: file.txt contains: (123) 456-7890 987-654-3210 (999) 888-7777
Output: (123) 456-7890 987-654-3210 (999) 888-7777
💡 Note: All three lines match valid phone number formats
Example 3 — No Valid Numbers
$ Input: file.txt contains: 555.123.4567 555 123 4567 +1-555-123-4567
Output:
💡 Note: None of these formats match the required patterns

Constraints

  • Each line contains at most one phone number
  • No leading or trailing whitespace on lines
  • Valid formats: (xxx) xxx-xxxx or xxx-xxx-xxxx where x is a digit

Visualization

Tap to expand
Valid Phone Numbers INPUT file.txt contents (555) 123-4567 OK 555-123-4567 OK 555.123.4567 X 5551234567 X Valid Formats: (xxx) xxx-xxxx xxx-xxx-xxxx x = any digit 0-9 4 lines to validate ALGORITHM STEPS Regex Pattern Matching 1 Define Pattern 1 ^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$ 2 Define Pattern 2 ^[0-9]{3}-[0-9]{3}-[0-9]{4}$ 3 Combine with OR pattern1 | pattern2 4 Apply grep/egrep Match each line Bash Command: grep -E "^(\([0-9]{3}\) | [0-9]{3}-)[0-9]{3}-[0-9]{4}$" FINAL RESULT Valid phone numbers Matching Process: (555) 123-4567 Matches pattern 1 555-123-4567 Matches pattern 2 555.123.4567 No match - uses dots 5551234567 No match - no separators OUTPUT: (555) 123-4567 555-123-4567 Key Insight: The regex uses alternation (|) to match two valid formats. The caret (^) and dollar ($) anchors ensure the entire line matches the pattern. Use grep -E for extended regex or egrep for simpler syntax. Key: [0-9]{3} matches exactly 3 digits, \( and \) match literal parentheses in the first pattern. TutorialsPoint - Valid Phone Numbers | Regular Expression Pattern Matching Approach
Asked in
Amazon 15 Microsoft 8
12.5K Views
Medium Frequency
~10 min Avg. Time
420 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen