1、组成
普通字符:普通字符串,没有特殊含义
特殊字符:在正则表达式中具有特殊的含义
正则表达式中常见的meta字符【特殊字符】
2、POSIX BRE【基本】与ERE【扩展】中都有的meta字符
/ :通常用于打开或关闭后续字符的特殊含义,如(...)【/是转义字符,去掉符号的特殊意义,()、{}等在shell中都有特殊的意义】
.和以及.的区别:
[root@localhost ~]# cat -n test.txt
1 gd
2 god
3
4 good
5 goood
6 goad
7
8 gboad
2.1、. :匹配任意单个字符(除null,即不能为空)
[root@localhost ~]# grep -n "." test.txt
1:gd
2:god
4:good
5:goood
6:goad
8:gboad
[root@localhost ~]# grep -n "go.d" test.txt
4:good
6:goad
2.2、 :匹配其前字符任意次,如o,可以是没有o或者一个o,也可以是多个o
[root@localhost ~]# grep -n "*" test.txt
[root@localhost ~]# grep -n "o*" test.txt
1:gd
2:god
3:
4:good
5:goood
6:goad
7:
8:gboad
[root@localhost ~]# echo "gbad" >>test.txt
[root@localhost ~]# echo "pbad" >>test.txt
[root@localhost ~]# echo "kgbad" >>test.txt
[root@localhost ~]# echo "poad" >>test.txt
[root@localhost ~]# grep -n "go*" test.txt 【o可以没有,o前面的g一定要匹配】
1:gd
2:god
4:good
5:goood
6:goad
8:gboad
9:gbad
11:kgbad
*2.3、. :匹配任意字符(匹配所有),可以为空**
[root@localhost ~]# grep -n ".*" test.txt
1:gd
2:god
3:
4:good
5:goood
6:goad
7:
8:gboad
9:gbad
10:pbad
11:kgbad
12:poad
[root@localhost ~]# grep -n "go.*" test.txt
2:god
4:good
5:goood
6:goad
[root@localhost ~]# grep -n "po.*" test.txt
12:poad
[root@localhost ~]# echo "pgoad" >>test.txt
[root@localhost ~]# grep -n "go.*" test.txt 【匹配go后存在任意字符,可为空】
2:god
4:good
5:goood
6:goad
13:pgoad
[root@localhost ~]#
[root@localhost ~]# grep -n "o.*" test.txt
2:god
4:good
5:goood
6:goad
8:gboad
12:poad
2.4、^ :匹配紧接着后面的正则表达式,以...为开头
[root@localhost tmp]# grep "^root" /etc/passwd
root:x:0:0:root:/root:/bin/bash
[root@localhost tmp]#
2.5、$ :匹配紧接着前面的正则表达式,以...结尾
[root@localhost tmp]# grep "bash$" /etc/passwd | head -1
新闻热点
疑难解答