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.
Example:
Assume that file.txt has the following content:
987-123-4567
123 456 7890
(123) 456-7890
Your script should output the following valid phone numbers:
987-123-4567
(123) 456-7890
cat > file.txt <<EOF
987-123-4567
(123) 456-7890
0(001) 345-0000
(001) 123-345
123 456 7890
EOF
匹配形如(xxx) xxx-xxxx or xxx-xxx-xxxx的模式
第一种,使用awk:
awk '/^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$/' file.txt
等同于
awk '/^(\([[:digit:]]{3}\) |[[:digit:]]{3}-)[[:digit:]]{3}-[[:digit:]]{4}$/' file.txt
用awk命令+RE解决。
开始及结尾处的 / 是正则表达式的定界符(在一些语言里要求使用)。
^ 表示无其他前缀。
$ 表示无其他后缀。
| 表示两种匹配选一个。
这里匹配中的 ( 需要转义。
第二种,用基本正则表达式:
grep "^\(([0-9]\{3\}) \|[0-9]\{3\}-\)[0-9]\{3\}-[0-9]\{4\}$" file.txt
等价于
grep "^\((\d\{3\}) \|\d\{3\}-\)\d\{3\}-\d\{4\}$" file.txt
第三种,用扩展的正则表达式:
grep -E "^(\([0-9]{3}\)\s|[0-9]{3}-)[0-9]{3}-[0-9]{4}$" file.txt
等价于
grep -E "^(\(\d{3}\)\s|\d{3}-)\d{3}-\d{4}$" file.txt
热门日志
分类
- Django(4)
- ssdb(1)
- Mac(7)
- C(1)
- memcache(1)
- Python(32)
- Vim(8)
- sed(2)
- ansible(3)
- awk(4)
- shell(3)
- about(1)
- git(9)
- bat(4)
- svn(0)
- docker(1)
- Tornado(1)
- go(2)
- 架构(18)
- Vue(1)
- game(2)
- Html(6)
- Java(8)
- Mysql(37)
- Ajax(2)
- Jsp(1)
- Struts(8)
- Linux(72)
- JavaScript(39)
- Staruml(0)
- Mouth(1)
- Php(102)
- Windows(8)
- Message(48)
- Lua(10)
- Compute(1)
- Redis(7)
- Nginx(12)
- Jquery(1)
- Apache(1)
- cocos2d-x(8)