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-xxxxxxx-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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code