Valid Phone Numbers
題目如下,大體就是給的電話號碼的格式只符合(xxx) xxx-xxxx or xxx-xxx-xxxx. (x爲數字)
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.
For example, assume that file.txt has the following content:
987-123-4567
123 456 7890
(123) 456-7890Your script should output the following valid phone numbers:
987-123-4567
(123) 456-7890
解題思路
這題不是非常的難,只需要用正則來匹配需要的格式顯示輸出就可以. 代碼如下:
awk '/^(\([0-9]{3}\) ){1}[0-9]{3}-[0-9]{4}$|^([0-9]{3}-){2}[0-9]{4}$/' file.txt
grep也有相似的功能, 那麼grep也可以進行輸出.
-P 選項是利用PERL的正則語法進行匹配
-o 是僅匹配這樣的模式
grep -P '^(\([0-9]{3}\) ){1}[0-9]{3}-[0-9]{4}$|^([0-9]{3}-){2}[0-9]{4}$' file.txt
上面的參數可以把-P變成-Po,結果也是被接受。- sed也是可以匹配正則,那麼sed也是有它的答案
sed -nr '/^(\([0-9]{3}\) ){1}[0-9]{3}-[0-9]{4}$|^([0-9]{3}-){2}[0-9]{4}$/p' file.txt