1、正则表达式与通配符
正则表达式:用来在文件中匹配符合条件的字符串,正则是包含匹配。grep、awk、sed等命令都可以支持正则表达式。
通配符:用来匹配符合条件的文件名,通配符是完全匹配。ls、find、cp这些命令不支持正则表达式,所以只能使用shell自己的通配符来进行匹配了。
2、基础正则表达式
元字符 | 作用 |
---|---|
* | 前一个字符匹配0次或任意多次; |
. | 匹配除了换行符外任意一个字符; |
^ | 匹配行首。例如:^hello会匹配以hello开头的行; |
$ | 匹配行尾。例如:hello&会匹配以hello结尾的行; |
[] | 匹配中括号中指定的任意一个字符,只匹配一个字符。 例如:[abcd] 匹配abcd中任意一个字母,[0-9] 匹配任意一位数字, [a-z][0-9] 匹配小写和一位数字构成的两位字符; |
[^] | 匹配除中括号的字符以外的任意一个字符。例如:[^0-9] 匹配任意一位非数字字符,[^a-z] 表示任意一位非小写字母; |
\ | 转义符。用于将特殊符号的含义取消。 |
\{n\} | 表示其前面的字符恰好出现n次。例如:[0-9]{4} 匹配4位数字; |
\{n,\} | 表示其前面的字符出现不小于n次。例如: [0-9]{2,} 表示两位及以上的数字; |
\{n,m\} | 表示其前面的字符至少出现n次,最多出现m次。例如: [a-z]{6,8} 匹配6到8位的小写字母; |
3、测试正则表达式
创建文件test_rule.txt,并且编辑内容。如下图所示:

3.1、* 前一个字符匹配0次,或任意多次
命令1:grep "h*" test_rule.txt
作用:匹配所有内容,包括空白行;

命令2:grep "hh*" test_rule.txt
作用:匹配至少包含有一个h的行;

命令3:grep "hhh*" test_rule.txt
作用:匹配至少包含两个连续h的字符串;

3.2、. 匹配除了换行符外任意一个字符
命令:grep "y..r" test_rule.txt
作用:匹配在y和r这两个字母之间一定有两个字符的字符串;

3.3、^匹配行首
命令:grep "^m" test_rule.txt
作用:搜索以m开头的行

3.4、$匹配行尾
命令:grep "h$" test_rule.txt
作用:搜索以h结尾的行

前面在 从零开始学习Linux(三十一):Shell脚本的执行方式 章节中提到过windows下shell脚本和Linux系统下shell脚本格式不同的问题。Linux系统下shell脚本格式是以$为行尾的,但是Windows下面shell脚本格式是以^M$为行尾的。
通过命令"cat -A test_rule.txt"可以查看,如下图所示:

如果是以^M$为行尾的,使用命令"grep "h$" test_rule.txt",是匹配不到任何数据的。
因此,当使用$匹配行尾且没有匹配到任何数据的时候,先考虑一下是否是由于文件格式的原因导致的。如果格式不一样,可以使用前面章节提到的命令转换一下文件格式。
3.5、[]匹配括号中指定的任意一个字符,只匹配一个字符
命令:grep "h[eh]h" test_rule.txt
作用: 匹配h和h字母中为e和h的行数据。

3.6、 [^] 匹配除中括号的字符以外的任意一个字符
命令:grep "^[^a-z]" test_rule.txt
作用:匹配不以小写字母开头的行

3.7、\ 转义符
命令:grep "\!$" test_rule.txt
作用:搜索以!结尾的行

3.8、\{n\} 表示其前面的字符恰好出现n次
命令:grep "o\{2\}" test_rule.txt
作用:匹配连续出现2次o的行数据

3.9、\{n,m\} 匹配其前面的字符至少出现n次最多出现m次
命令:grep "o\{3,5\}" test_rule.txt
作用:匹配连续出现最少3次,最多5次的行数据

网友评论