grep 用法和正则表达式(二)

grep 用法和正则表达式(二)

学习目标

grep 更深入的用法

grep 结合正则表达式的实际示例

灵活掌握收索技巧

1、 匹配开头和结尾字符

格式:grep {^string | string$} filename

示例:grep “^hello” test.txt  匹配hello开头的字符串; (字符串开头)

         grep  “hello&” test.txt 匹配hello结尾的字符串;      (字符串开头)

      grep  “^[a-z]e$” test.txt  匹配a~z开头e结尾的内容 (字符开头)

      grep  “^[^a-z]e$” test.txt  匹配非a~z开头e结尾的内容 (字符开头)

2、 匹配整个单词

格式: grep ‘\bhello\b’ filename

3、 . ? + 和 * 的用处

格式:grep {… | ? | . * } filename

. 匹配单个字符能匹配空格;

* 匹配任意字符或字符串的重复多次;

. + 字符必须出现1次;

grep –E ‘n.+’ test.txt  -E 为grep 拓展;

. ?  字符出现0次或1次;

grep –E ‘n.?’ test.txt  -E 为grep 拓展

注意: grep 不支持+ ? 元字符 必须要加上-E选项;

 

Perl 的正则表达-p;

.*的贪婪匹配

grep –p ‘tom.*i’  test.txt    以tom开头.*中间任意多个字符匹配并以i结尾;

.*?惰性匹配

grep –p ‘tom.*i?’  test.txt    以tom开头.*中间任意多个字符匹配并以第一个i结尾;

4、 grep 的标签

格式:grep ‘\(str\)\(\)(\)[other]\1’  filename  \1表示标签在第一组;()是需要转义的;

          grep ‘\(tom\)..\1’  test.txt  以tom标签开始,\1(tom)结尾,中间任意匹配两个字符;

          grep ‘\(tom\)\(hello\)..\1’  test.txt 匹配多个标签;

5、 grep 中的pattern搜索

格式1:grep ‘[str]\{1\}’  filename

grep ‘tom\{2\}’ test.txt 表示以to开头,m出现两次;

grep ‘\(tom\)\{2\}’ test.txt  加上tom标签;表示匹配两次tom;

格式2:grep ‘[str]\{1,\}’  filename

grep ‘\(tom\)\{1,\}’ test.txt   表示标签tom至少出现一次;

格式3:grep ‘[str]\{1,3\}’  filename

grep ‘\(tom\)\{1,3\}’ test.txt     表示匹配出现1~3次tom;

grep ‘^\(tom\)\{1,3\}’ test.txt    表示匹配连续出现1~3次tom开头;

转载于:https://www.cnblogs.com/Bright-Ho/p/5457975.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值