LeetCode(193. Valid Phone Numbers)(sed用法)

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

题解:验证字符串是否为正确电话号码格式

解法一: awk

注:

  • awk '/正则表达式/' file.txt
  • [0-9]{3}: 表示 0~9数字匹配三次
  • ([0-9]{3}-|\([0-9]{3}\)): 表示为一组, | 表示为或
awk '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/' file.txt 

解法二:grep

 注意:\d{3}来表示[0-9]{3};-P:逐行匹配

grep -P '^(\d{3}-|\(\d{3}\) )\d{3}-\d{4}$' file.txt 

解法三:sed

补充sed用法:

简介:sed是流编辑工具,用来对文本进行过滤和替换。sed通过输入读取文件内容,但 一次仅读取一行内容 进行某些指令处理后输出,sed更适合于处理大数据文件。

基本原理:sed在处理文本文件的时候,会在内存上创建一个模式空间,然后把这个文件的每一行调入模式空间用相应的命令处理,处理完输出;接着处理下一行,直到最后。

基本语法:

(1)sed [选项]  [定址commands] [inputfile]

关于定址:

  • 定址可以是0个、1个、2个;通知sed去处理文件的哪几行。
  • 0个:没有定址,处理文件的所有行
  • 1个:行号,处理行号所在位置的行
  • 2个:行号、正则表达式,处理被行号或正则表达式包起来的行

(2)选项:

       --version       显示sed版本hao

       --help            显示帮助文档

       -n                  关闭默认输出,默认将自动打印所有行

       -e                  多点编辑,允许多个脚本指令被执行。

       -r                  支持扩展正则+ ? () {} |

       -i                   可以修改原文件,慎用!

       -f                  支持使用脚本

命令:

       p         打印行

       d         删除行

       s         替换

       n         替换第几个匹内容

       w        另存为

       a         之后添加一行

       i         当前行之前插入文本

       y        替换匹配内容

(p和-n合用)

 

(d:删除)

(s/pattern/replacement/flags)

题解:

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

猜你喜欢

转载自www.cnblogs.com/douzujun/p/10416060.html