grep -E 主要是用来支持扩展正则表达式,比如 | 符号,用于grep多条件查询,并非是使用标准正则表达式。
grep -P 主要让grep使用perl的正则表达式语法,因为perl的正则更加多元化,能实现更加复杂的场景。最典型的用法是"匹配指定字符串之间的字符"。
示例如下:
打印test.file文件中含有2018 或 2019 或 2020字符串的行
[root@localhost ~]# grep -E "2018|2019|2020" test.file
如下想在一句话"Hello,my name is kevin" 中匹配中间的一段字符串 "my name is",可以这样写正则表达式:
[root@localhost ~]# echo "Hello,my name is kevin"
Hello,my name is kevin
[root@localhost ~]# echo "Hello,my name is kevin"|grep -P '(?<=Hello)'
Hello,my name is kevin
[root@localhost ~]# echo "Hello,my name is kevin"|grep -P '(?<=Hello).*(?= kevin)'
Hello,my name is kevin
[root@localhost ~]# echo "Hello,my name is kevin"|grep -Po '(?<=Hello).*(?= kevin)'
,my name is
[root@localhost ~]# echo "Hello,my name is kevin"|grep -P '(?<=Hello,).*(?= kevin)'
Hello,my name is kevin
[root@localhost ~]# echo "Hello,my name is kevin"|grep -Po '(?<=Hello,).*(?= kevin)'
my name is
这里千万注意下:正则中的 ?= 、?<= 、?! 、?<! 四个表达的意思。结合grep使用的时候,一定要跟上-P参数,"grep -P" 表示后面跟正则表达式。
?= 表示询问后面跟着的东西是否等于这个。
?<= 表示询问是否以这个东西开头。
?! 表示询问后面跟着的东西是否不是这个。
?<! 表示询问是否不是以这个东西开头 。
示例:grep -P后面跟上面四种正则时,要在引号里使用小括号进行匹配。
[root@localhost ~]# cat test.txt
bac
ab
bb
bch
ban
[root@localhost ~]# grep -P 'b(?=a)' test.txt
bac
ban
[root@localhost ~]# grep -P '(?<=a)' test.txt
bac
ab
ban
[root@localhost ~]# grep -P '(?<=a)b' test.txt
ab
[root@localhost ~]# grep -P 'b(?!a)' test.txt
ab
bb
bch
[root@localhost ~]# grep -P '(?<!a)b' test.txt
bac
bb
bch
ban
按照上面的思路,如果想要取得本机ip地址,可以如下操作:
[root@localhost ~]# ifconfig eth0
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 172.16.60.232 netmask 255.255.255.0 broadcast 172.16.60.255
inet6 fe80::e825:b3ff:fef6:1398 prefixlen 64 scopeid 0x20<link>
ether ea:25:b3:f6:13:98 txqueuelen 1000 (Ethernet)
RX packets 22911237 bytes 4001968461 (3.7 GiB)
RX errors 0 dropped 17058008 overruns 0 frame 0
TX packets 670762 bytes 98567533 (94.0 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
[root@localhost ~]# ifconfig eth0|grep -P "(?<=inet).*(?=netmask)"
inet 172.16.60.232 netmask 255.255.255.0 broadcast 172.16.60.255
[root@localhost ~]# ifconfig eth0|grep -Po "(?<=inet).*(?=netmask)"
172.16.60.232