Bash script check a valid phone number

We are given a text file calledsample.txt that contains la ist of phone numbers ( each is per line), we will write a bash script to check which one is a valid phone numbers.

Valid phone number format as: (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 sample.txt has the following content:

123 456 7890
(123) 456-7890

Our script should output the following valid phone numbers:

(123) 456-7890
We appreciate your comments as the answer for “bash script check a valid phone number

The Regular Expression is:

^((\([0-9]{3}\) )|([0-9]{3}\-))[0-9]{3}\-[0-9]{4}$
  • ^ denotes the start of the string.
  • $ denotes the end of the string.
  • [0-9] means numbers
  • {3} means 3 numbers and {4} means 4 numbers
  • (A)|(B) means match pattern A or pattern B
  • \( escapes the bracket

So, you can use grep with parameter -P to match the pattern.

grep -P "^((\([0-9]{3}\) )|([0-9]{3}\-))[0-9]{3}\-[0-9]{4}$" file.txt

Alternatively, you can use awk or sed.

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

So we can use
[[:digit:]]{3} or \d{3} to replace [0-9]{3}.

Leave a Reply

Your email address will not be published. Required fields are marked *