浙江省高等学校教师教育理论培训

微信搜索“教师资格证岗前培训”小程序

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

学习Grep,Sed中的正则 | 火丁笔记

 


学习Grep,Sed中的正则

 

正则要是几天不学习不用功,肯定会忘得一干二净,下面聊聊Grep,Sed中的正则。

 

问题:从一个文本文件里筛选出含有电话号码的行,电话号码是由七位或者八位阿拉伯数字组成(开头不是零),并且被单引号或者双引号包裹。

鉴于问题的需要,先杜撰一份数据:

shell> cat /path/to/data.txt
'7654321'
'7654321"
"87654321"
"87654321'

失败的尝试

shell> grep "(['\"])[1-9][0-9]{6,7}\1" /path/to/data.txt
grep: Invalid back reference
shell> sed -n "/(['\"])[1-9][0-9]{6,7}\1/p" /path/to/data.txt
sed: -e expression #1, char 25: Invalid back reference

成功的尝试

使用Basic Regular Expressions (BRE)

shell> grep "\(['\"]\)[1-9][0-9]\{6,7\}\1" /path/to/data.txt
'7654321'
"87654321"
shell> sed -n "/\(['\"]\)[1-9][0-9]\{6,7\}\1/p" /path/to/data.txt
'7654321'
"87654321"

使用Extended Regular Expressions (ERE)

shell> grep -E "(['\"])[1-9][0-9]{6,7}\1" /path/to/data.txt
'7654321'
"87654321"
shell> sed -n -r "/(['\"])[1-9][0-9]{6,7}\1/p" /path/to/data.txt
'7654321'
"87654321"

总结:Grep和Sed同时支持BRE和ERE两种正则,缺省情况下,Grep和Sed使用的都是BRE正则,通过增加命令参数(grep -E / sed -r),Grep和Sed可以支持ERE正则。

BTW:Regular expression From Wikipedia, the free encyclopedia

 


This entry was posted in Technical and tagged Grep, Linux, Regex, Sed, Shell by 老王. Bookmark the permalink.

 

posted on 2012-08-01 20:35  lexus  阅读(442)  评论(0编辑  收藏  举报