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: Filter by FormatInput File(555) 123-4567555-123-4567555.123.45675551234567555 123 4567(999) 888-7777+1-555-123-4567Regex Filter^(\([0-9]{3}\) [0-9]{3}-[0-9]{4}|[0-9]{3}-[0-9]{3}-[0-9]{4})$Two Valid FormatsValid Output(555) 123-4567555-123-4567(999) 888-77773 matchesBash Command: grep -E '^(\([0-9]{3}\) [0-9]{3}-[0-9]{4}|[0-9]{3}-[0-9]{3}-[0-9]{4})$' file.txt
Understanding the Visualization
1
Input File
Text file with mixed phone number formats
2
Pattern Match
Apply regex to identify valid formats
3
Output
Print only lines matching (xxx) xxx-xxxx or xxx-xxx-xxxx
Key Takeaway
🎯 Key Insight: Regular expressions provide a concise way to match multiple string patterns simultaneously
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