Valid Phone Numbers
EASYDescription
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
Approaches
Checkout 4 different approaches to solve Valid Phone Numbers. Click on different approaches to view the approach and algorithm in detail.
Pure Bash `while` loop
This approach uses a while loop in bash to read the file line by line. For each line, it uses the [[ ... =~ ... ]] conditional expression to test if the line matches the required regular expression for a valid phone number. If it matches, the line is printed to standard output.
Algorithm
-
- Start a
whileloop to readfile.txtline by line into a variableline.
- Start a
-
- For each
line, use the[[ ... =~ ... ]]operator to perform a regex match.
- For each
-
- The regex checks for two patterns separated by
|(OR):\([0-9]{3}\) [0-9]{3}-[0-9]{4}or[0-9]{3}-[0-9]{3}-[0-9]{4}.
- The regex checks for two patterns separated by
-
- The entire pattern is anchored with
^and$to ensure the whole line matches.
- The entire pattern is anchored with
-
- If the line matches the regex, print the line.
-
- Continue until all lines are processed.
The script reads file.txt line by line using while read -r line. The -r option prevents backslash interpretation. Inside the loop, an if statement checks the line against a regular expression. The regex ^(\([0-9]{3}\) [0-9]{3}-[0-9]{4}|[0-9]{3}-[0-9]{3}-[0-9]{4})$ is used to validate the two possible phone number formats. The ^ and $ anchors ensure that the entire line must match one of the formats. If the condition is true, echo "$line" prints the valid phone number. This can be written as a one-liner using the && operator.
while read -r line; do [[ "$line" =~ ^(\([0-9]{3}\) [0-9]{3}-[0-9]{4}|[0-9]{3}-[0-9]{3}-[0-9]{4})$ ]] && echo "$line"; done < file.txt
Complexity Analysis
Pros and Cons
- No external utilities are needed; it's a pure bash solution.
- Significantly slower than using dedicated text-processing tools like
grep,sed, orawk, especially for large files. - The one-liner syntax can be less readable.
Video Solution
Watch the video walkthrough for Valid Phone Numbers
Similar Questions
5 related questions you might find useful
Tags:
No tags found.
Companies:
Subscribe to Scale Engineer newsletter
Learn about System Design, Software Engineering, and interview experiences every week.
No spam, unsubscribe at any time.