shell编程教学(三)| Linux三剑客之grep

grep简介

grep (缩写来自Globally search a Regular Expression and Print)是一种强大的文本搜索工具,它能使用特定模式匹配(包括正则表达式)搜索文本,并默认输出匹配行。

一、grep的常见用法

grep root passwd          >> 显示 包含root 的行
grep ^root passwd         >> 显示 以root开头 的行
grep root$ passwd         >> 显示 以root结尾 的行
grep -i root passwd       >> -i表示忽略大小写
grep -v root passwd       >> 显示不包含root(匹配文本)的所有行
grep -E "^root|bash$" passwd  >> -E表示扩展的正则表达式,以root开头或者以bash结尾的行

注意:正规的 grep 不支持扩展的正则表达式 , 竖线是用于表示”或”的扩展正则表达式元字符 , 正规的 grep 无法识别,egrep 命令等同于‘grep -E
在这里插入图片描述

小试牛刀
在/mnt下的passwd中找出root位于中间的行
在这里插入图片描述

二、grep的正则表达式

[root@allen mnt]# grep 'r..t' Grep_Test    >> 表示匹配含从r到t间有两个字符的行

[root@allen mnt]# grep 'r*t' Grep_Test     >> 表示匹配含从r到t间有任意个字符的行

[root@allen mnt]# grep 'ro*t' Grep_Test    >> 表示匹配含从r到t间有任意个o的行

如有什么不理解,请看截图中的变化
在这里插入图片描述

[root@allen mnt]# grep -E 'ri{1,}t' Grep_Test >> 表示匹配含从r到t间有1到无穷个 i 的行

[root@allen mnt]# grep -E 'ri{1,2}t' Grep_Test  >> 表示匹配含从r到t间有1到2个 i 的行

[root@allen mnt]# grep -E 'ri?t' Grep_Test   >> 表示匹配含从r到t间有0个或者1个 i 的行

[root@allen mnt]# grep -E 'ri{,2}t' Grep_Test   >> 表示匹配含从r到t间有0到2个 i 的行

在这里插入图片描述

[root@allen mnt]# grep -E 'ri+t' Grep_Test   
			 	= grep -E 'ri{1,}t' Grep_Test

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44297303/article/details/88193244