1. Valid Phone Numbers

Given a text file file.txt that contains 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.


Assume that file.txt has the following content:

123 456 7890
(123) 456-7890

Your script should output the following valid phone numbers:

(123) 456-7890

Solution 1

# Read from the file file.txt and output all valid phone numbers to stdout.
cat file.txt | grep -P '(^\(\d{3}\) \d{3}-\d{4}$)|(^\d{3}-\d{3}-\d{4}$)' 
grep -P '^(\d{3}-|\(\d{3}\) )\d{3}-\d{4}$' file.txt
  • \Escape character: to escape next one trailing character
   -P, --perl-regexp
          Interpret the pattern as a Perl-compatible regular expression (PCRE).  
          This is experimental and grep -P may warn of unimplemented features.

Solution 2

sed -n -r '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/p' file.txt
   -n, --quiet, --silent
         suppress automatic printing of pattern space

  -E, -r, --regexp-extended
         use extended regular expressions in the script (for portability use POSIX -E).

Solution 3

awk '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/' file.txt

References and recommended readings:



This article follows the Creative Commons copyright agreement CC by-nc 4.0, which requires signature, non-commercial and consistent. It can be reproduced on the basis of CC by-nc 4.0, but please indicate the source in the form of hyperlink. The article only represents the author’s knowledge and opinions. If there are different opinions, you can reply and discuss them.