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开头;

posted @   Bright-Ho~蜗牛~  阅读(724)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示