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:

Our script should output the following valid phone numbers:

We appreciate your comments as the answer for “bash script check a valid phone number

The Regular Expression is:

  • ^ 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.

Alternatively, you can use awk or sed.

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

Leave a Reply

Notify of