一、正则表达式

image.png
1.1、字符匹配

image.png
[root@localhost /home/unnet/data]#grep "r..t" /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
dockerroot:x:998:995:Docker User:/var/lib/docker:/sbin/nologin
[root@localhost /home/unnet/data]#grep "[[:digit:]]" /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
1.2、匹配次数

image.png
[root@localhost /home/unnet/data]#cat e.txt
gogle
google
gooooooogle
coogle
eooooogle
aooogle
##匹配至少两个o字母
[root@localhost /home/unnet/data]#grep "gooo*gle" e.txt
google
gooooooogle
###匹配至少一个o字母及以上
[root@localhost /home/unnet/data]#grep "go\+gle" e.txt
gogle
google
gooooooogle
####匹配两个o字母的字符串
[root@localhost /home/unnet/data]#grep "go\{2,2\}gle" e.txt
google
1.3、位置锚定

image.png

image.png
###匹配google字符串
[root@localhost /home/unnet/data]#grep "^google$" e.txt
google
###显示排除以#开头的内容
[root@localhost /home/unnet/data]#grep -v "^#" /etc/fstab
/dev/mapper/centos-root / xfs defaults 0 0
UUID=34077afd-de96-437f-8cdf-3590f3fac51f /boot xfs defaults 0 0
/dev/mapper/centos-swap swap swap defaults 0 0
###单词词首为goo
[root@localhost /home/unnet/data]#grep "\<goo" e.txt
google
gooooooogle
###单词词尾为gle
[root@localhost /home/unnet/data]#grep "gle\>" e.txt
gogle
google
gooooooogle
coogle
eooooogle
aooogle
[root@localhost /home/unnet/data]#cat > f1
xya^Hz ^H^H
^C
[root@localhost /home/unnet/data]#cat > f1
xyz xyz
abc xyz abc xyz abc
xyz xyz
abc abc
^C
[root@localhost /home/unnet/data]#cat f1
xyz xyz
abc xyz abc xyz abc
xyz xyz
abc abc
[root@localhost /home/unnet/data]#grep "\(abc\).*\(xyz\).*\1" f1
abc xyz abc xyz abc
[root@localhost /home/unnet/data]#grep "\(abc\).*\(xyz\).*\2" f1
abc xyz abc xyz abc
[root@localhost /home/unnet/data]#grep "\(abc\).*\1" f1
abc xyz abc xyz abc
abc abc
[root@localhost /home/unnet/data]#grep "^\(a\|b\)" /etc/passwd
bin:x:1:1:bin:/bin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
二、扩展正则表达式

image.png

image.png

image.png

image.png
###取基名
[root@localhost /home/unnet/data]#basename /etc/rc.d/init.d/functions
functions
###取目录名
[root@localhost /home/unnet/data]#dirname /etc/rc.d/init.d/functions
/etc/rc.d/init.d
###扩展正则表达式
[root@localhost /home/unnet/data]#echo "/etc/rc.d/init.d/functions" | grep -Eo "[^/]+$"
functions
###扩展正则表达式
[root@localhost /home/unnet/data]#echo "/etc/rc.d/init.d/functions" | grep -Eo ".*/"
/etc/rc.d/init.d/
###基本正则表达式
[root@localhost /home/unnet/data]#echo "/etc/rc.d/init.d/functions" | grep -o "[^/]\+$"
functions
网友评论