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 or xxx-xxx-xxxx. (x means a digit)
You may also assume each line in the text file must not contain leading or trailing white spaces.
Example:
Assume that file.txt has the following content:
987-123-4567 123 456 7890 (123) 456-7890
Your script should output the following valid phone numbers:
987-123-4567 (123) 456-7890
The #193 Valid Phone Numbers problem focuses on filtering lines from a file that match specific phone number formats. The valid formats typically include xxx-xxx-xxxx and (xxx) xxx-xxxx. Since this is a Shell problem, the most effective approach is to use command-line text processing tools such as grep, awk, or sed.
The key idea is to apply a regular expression that strictly matches the required patterns. For example, extended regular expressions with grep -E can validate both allowed formats by checking digit counts, parentheses placement, spaces, and hyphens. Each line from the input file is scanned, and only those matching the pattern are printed.
This approach works efficiently because the file is processed line by line, making it scalable for large inputs. The time complexity is O(n), where n is the number of lines in the file, while the space complexity remains O(1) since no additional data structures are required beyond streaming the input.
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Regex filtering using grep/awk | O(n) | O(1) |
CrioDo
Watch expert explanations and walkthroughs
Jot down your thoughts, approach, and key learnings
Problems like Valid Phone Numbers are less common in core algorithm interviews but can appear in scripting or system-oriented rounds. They test familiarity with shell tools and pattern matching.
This problem does not require complex data structures. Since it focuses on text filtering, command-line utilities combined with regular expressions are sufficient for processing each line of the file.
The optimal approach is to use regular expressions with shell tools like grep, awk, or sed. A well-defined regex pattern can match the allowed phone number formats and filter the valid lines efficiently.
Regular expressions allow precise pattern matching for phone number formats such as xxx-xxx-xxxx and (xxx) xxx-xxxx. They ensure only correctly formatted numbers are selected from the input file.