[Bash]LeetCode193. 有效電話號碼 | Valid Phone Numbers

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-htetmqbf-md.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

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.git

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)github

You may also assume each line in the text file must not contain leading or trailing white spaces.bash

Example:微信

Assume that file.txt has the following content:app

987-123-4567
123 456 7890
(123) 456-7890

Your script should output the following valid phone numbers:spa

987-123-4567
(123) 456-7890

給定一個包含電話號碼列表(一行一個電話號碼)的文本文件 file.txt,寫一個 bash 腳本輸出全部有效的電話號碼。code

你能夠假設一個有效的電話號碼必須知足如下兩種格式: (xxx) xxx-xxxx 或 xxx-xxx-xxxx。(x 表示一個數字)orm

你也能夠假設每行先後沒有多餘的空格字符。htm

示例:

假設 file.txt 內容以下:

987-123-4567
123 456 7890
(123) 456-7890

你的腳本應當輸出下列有效的電話號碼:

987-123-4567
(123) 456-7890

8ms
1 # Read from the file file.txt and output all valid phone numbers to stdout.
2 grep -P '^(\d{3}-|\(\d{3}\) )\d{3}-\d{4}$' file.txt

12ms

1 # Read from the file file.txt and output all valid phone numbers to stdout.
2 
3 grep -P '^\([0-9]{3}\)\s[0-9]{3}-[0-9]{4}$|^[0-9]{3}-[0-9]{3}-[0-9]{4}$' file.txt

12ms

1 # Read from the file file.txt and output all valid phone numbers to stdout.
2 sed -n -r '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/p' file.txt

12ms

1 # Read from the file file.txt and output all valid phone numbers to stdout.
2 egrep "(^[0-9]{3}-[0-9]{3}-[0-9]{4}$)|(^\([0-9]{3}\)\s[0-9]{3}-[0-9]{4}$)" file.txt
相關文章
相關標籤/搜索