ime2224的个人空间 https://blog.eetop.cn/1101565 [收藏] [复制] [分享] [RSS]

空间首页 动态 记录 日志 相册 主题 分享 留言板 个人资料

日志

(转)linux命令之grep(三)

已有 449 次阅读| 2014-8-19 18:25 |个人分类:LINUX

1、 限定连续 RE 字符范围 {}

我们可以利用 . RE 字符及 * 来配置 0 个到无限多个重复字节, 那如果我想要限制一个范围区间内的重复字节数呢?

举例来说,我想要找出两个到五个 o 的连续字串,该如何作?这时候就得要使用到限定范围的字符 {} 了。 但因为 { } 的符号在 shell 是有特殊意义的,因此, 我们必须要使用字符   \ 来让他失去特殊意义才行。 至於 {} 的语法是这样的,假设我要找到两个 o 的字串,可以是:

[root@www ~]# grep -n 'o\{2\}' regular_express.txt

1:"Open Source" is a good mechanism to develop programs.

2:apple is my favorite food.

3:Football game is not use feet only.

9:Oh! The soup taste good.

18:google is the best tools for search ke

19:goooooogle yes!

假设我们要找出 g 后面接 2 5 o ,然后再接一个 g 的字串,他会是这样:

[root@www ~]# grep -n 'go\{2,5\}g' regular_express.txt

18:google is the best tools for search keyword.

如果我想要的是 2 o 以上的 goooo....g 呢?除了可以是 gooo*g ,也可以是:

[root@www ~]# grep -n 'go\{2,\}g' regular_express.txt

18:google is the best tools for search keyword.

19:goooooogle yes!

2、 扩展grep(grep -E 或者 egrep)

使用扩展grep的主要好处是增加了额外的正则表达式元字符集。

 

打印所有包含NWEA的行。如果不是使用egrep,而是grep,将不会有结果查出。

    # egrep 'NW|EA' testfile    

    northwest       NW      Charles Main        3.0     .98     3       34

    eastern         EA      TB Savage           4.4     .84     5       20

对于标准grep,如果在扩展元字符前面加\grep会自动启用扩展选项-E

#grep 'NW\|EA' testfile

northwest       NW      Charles Main        3.0     .98     3       34

eastern         EA      TB Savage           4.4     .84     5       20

搜索所有包含一个或多个3的行。

# egrep '3+' testfile

# grep -E '3+' testfile

# grep '3\+' testfile       

#3条命令将会

northwest       NW      Charles Main          3.0     .98     3       34

western         WE      Sharon Gray           5.3     .97     5       23

northeast       NE      AM Main Jr.           5.1     .94     3       13

central         CT      Ann Stephens          5.7     .94     5       13

搜索所有包含0个或1个小数点字符的行。

# egrep '2\.?[0-9]' testfile

# grep -E '2\.?[0-9]' testfile

# grep '2\.\?[0-9]' testfile

#首先含有2字符,其后紧跟着0个或1个点,后面再是09之间的数字。

western         WE       Sharon Gray          5.3     .97     5       23

southwest       SW      Lewis Dalsass         2.7     .8      2       18

eastern         EA       TB Savage             4.4     .84     5       20

搜索一个或者多个连续的no的行。

# egrep '(no)+' testfile

# grep -E '(no)+' testfile

# grep '\(no\)\+' testfile   #3个命令返回相同结果,

northwest       NW      Charles Main        3.0     .98    


点赞

评论 (0 个评论)

facelist

您需要登录后才可以评论 登录 | 注册

  • 关注TA
  • 加好友
  • 联系TA
  • 0

    周排名
  • 0

    月排名
  • 0

    总排名
  • 2

    关注
  • 1

    粉丝
  • 0

    好友
  • 2

    获赞
  • 0

    评论
  • 490

    访问数
关闭

站长推荐 上一条 /1 下一条

小黑屋| 关于我们| 联系我们| 在线咨询| 隐私声明| EETOP 创芯网
( 京ICP备:10050787号 京公网安备:11010502037710 )

GMT+8, 2024-5-18 09:27 , Processed in 0.015607 second(s), 8 queries , Gzip On, Redis On.

eetop公众号 创芯大讲堂 创芯人才网
返回顶部