1、組成
普通字符:普通字符串,沒有特殊含義
特殊字符:在正則表達式中具有特殊的含義
正則表達式中常見的meta字符【特殊字符】
2、POSIX BRE【基本】與ERE【擴展】中都有的meta字符
/ :通常用于打開或關(guān)閉后續(xù)字符的特殊含義,如(...)【/是轉(zhuǎn)義字符,去掉符號的特殊意義,()、{}等在shell中都有特殊的意義】
.和以及.的區(qū)別:
[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、$ :匹配緊接著前面的正則表達式,以...結(jié)尾
[root@localhost tmp]# grep "bash$" /etc/passwd | head -1
新聞熱點
疑難解答
圖片精選