Shell:文本处理(grep/sed/awk/find)

一.grep文本过滤命令

1.grep

全面搜索研究正则表达式并显示出来

grep命令是一种强大的文本搜索工具,根据用户指定的“模式”对目标文本进行匹配检查,打印到匹配的行。 由正则表达式或者字符及基本文本字符所编写的过滤条件

2.grep的格式

grep 匹配条件 处理文件

3.grep中字符的匹配位置设定

^关键字 以“关键字“开头
关键字$ 以关键字结尾
<关键字 关键字前没有字符
关键字> 关键字后面没有字符
<关键字> 关键字前后均没有字符
[root@shell mnt]# cp /etc/passwd  .
[root@shell mnt]# ls
passwd
[root@shell mnt]# vim passwd

在这里插入图片描述

[root@shell mnt]# grep root passwd
[root@shell mnt]# grep -i root passwd  ##过滤root其中包含大写
[root@shell mnt]# grep -i "\<root" passwd  ##过滤root其中包含大写,并且以root开头
[root@shell mnt]# grep -i "\<root\>" passwd   #root前后都不含有附加字符
[root@shell mnt]# grep -i "^\<root\>" passwd  #在上一步的基础上以root开头的

在这里插入图片描述

[root@shell mnt]# grep -i "^root" passwd  #同上
[root@shell mnt]# grep -i "^\<root\>$" passwd #以root开头以root结尾
[root@shell mnt]# grep -i "\<root\>$" passwd  #以root结尾的

在这里插入图片描述
4.grep中的正则表达式

grep r... file   #以r开头的任意3个字符的行
grep r...t  file    #以r开头,t结尾的,并且中间有任意三个字符的行
grep  ..t  file   #以t结尾的,前面有3个字符的行 

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
5.grep正则表达式与扩展正则表达式

  • 正规的grep不支持扩展的正则表达式
  • | 是用于表示或的扩展正则表达式字符,正规的grep无法识别
  • 加 \ ,这个字符就被翻译成扩展的正则表达式,就像egrep和grep -E一样。
[root@shell mnt]# grep -iE "^root\>|\<root$" passwd  #从开始的root和结束时
[root@shell mnt]# egrep -i "^root\>|\<root$" passwd  #或者

在这里插入图片描述

[root@shell mnt]# grep -iE "^root\>|\<root$" passwd -v  #不是以root开头和root结尾的即中间的
[root@shell mnt]# grep -iE "^root\>|\<root$" passwd -v | grep  root   #不是以root开头和root结尾的即中间的
[root@shell mnt]# grep -iE "^root\>|\<root$" passwd -v | grep  "\<root\>"

在这里插入图片描述
6.grep中字符匹配次数的设定

.* 关键字之间匹配任意字符
* 字符出现【0-任意次】
? 字符出现[ 0-1]次
+ 字符出现1到任意次
{n} 字符出现n次
|{m,n} 字符出现【最少出现m次,最多出现n次
{0,n} 字符出现0到n次
{m,} 字符出现至少m次
xy{n}xy 关键字出现n次

在这里插入图片描述
在这里插入图片描述

[root@shell mnt]# grep -E "x*" test  #过滤x无数次

在这里插入图片描述

[root@shell mnt]# grep -E "x?*" test 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值