正则的主要作用 处理文本内容
基础正则
^ 定位起始头的
[root@RainGod ~]# grep '^y' /etc/passwd
yt03:x:1002:1002::/home/yt03:/bin/bash
yt01:x:1003:1003::/home/yt01:/bin/bash
yt02:x:1004:1004::/home/yt02:/bin/bash
$ 定位结束尾部信息
[root@RainGod ~]# grep 'n$' /etc/passwd
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
^$ 空行
[root@RainGod ~]# cat test.txt
11
22
[root@RainGod ~]# grep '^$' test.txt
[root@RainGod ~]# grep -v '^$' test.txt
11
22
. 点 匹配任意一个字符
[root@RainGod ~]# cat test.txt
11
22
[root@RainGod ~]# grep "." test.txt -o
1
1
2
2
* 匹配*号前面的字符出现0次或者多次
[root@RainGod ~]# cat test.txt
11
22
[root@RainGod ~]# grep ".*" test.txt -o
11
22
.* 匹配所有内容
[root@RainGod ~]# cat test.txt
11
i like fsfs fsf ball
22
[root@RainGod ~]# grep "i.*ball" test.txt
i like fsfs fsf ball fsdfsd fsdfsd
[root@RainGod ~]# grep "i.*ball" test.txt -o
i like fsfs fsf ball
转义符
[root@RainGod ~]# grep '.' test.txt
11 .
i like fsfs fsf ball fsdfsd fsdfsd .
22
[root@RainGod ~]# grep '.' test.txt
11 .
i like fsfs fsf ball fsdfsd fsdfsd .
[] 或者的意思 匹配多个信息 按照每一个字符匹配
[root@RainGod ~]# grep '.' test.txt
11 .
i like fsfs fsf ball fsdfsd fsdfsd .
22
[root@RainGod ~]# grep '.' test.txt
11 .
i like fsfs fsf ball fsdfsd fsdfsd .
[root@RainGod ~]# grep "[1]" test.txt
11 .
[root@RainGod ~]# grep "[1i]" test.txt
11 .
i like fsfs fsf ball fsdfsd fsdfsd .
[]取反
[root@RainGod ~]# grep "^[^#]" /etc/selinux/config
SELINUX=disabled
SELINUXTYPE=targeted
[root@RainGod ~]# awk '/^[^#]/' /etc/selinux/config
SELINUX=disabled
SELINUXTYPE=targeted
[root@RainGod ~]# sed -n '/^[^#]/p' /etc/selinux/config
SELINUX=disabled
SELINUXTYPE=targeted
扩展正则
+ 表示前面一个字符连续出现1次及以上 *表示前面一个字符连续出现0次及以上
[root@RainGod ~]# egrep 'l+' test.txt -o
l
ll
[root@RainGod ~]# grep 'l*' test.txt
11 .
i like fsfs fsf ball fsdfsd fsdfsd .
22
[root@famous-machine-1 ~]# egrep "[0-9]+" test.txt -o
110102199805296211
110102199805299877
110102199805299076
110102199805298559
110102199805296836
11010219980529817
| 匹配多个信息时 当做或者使用
[root@famous-machine-1 ~]# egrep "oldboy|oldgirl" test.txt
冯 oldboy
oldgirl
() 把括号里的内容当做一个整体
[root@famous-machine-1 ~]# egrep "(oldboy|oldgirl)" test.txt
冯 oldboy
oldgirl
{n,m} 花括号指定匹配的次数 最少出现n次 最多出现m次
[root@RainGod ~]# cat test.txt
o
o
oo
ooo
oooo
ooooo
[root@RainGod ~]# egrep "o{1,4}" test.txt -o
o
o
oo
ooo
oooo
oooo
o
? 匹配0次或一次
[root@RainGod ~]# grep "go*d" test1.txt -o
gd
god
good
goood
gooood
[root@RainGod ~]# egrep "go+d" test1.txt -o
god
good
goood
gooood
[root@RainGod ~]# egrep "go?d" test1.txt -o
gd
god
正则取ip
grep
[root@famous-machine-1 ~]# ip a s eth0|grep inet|egrep "([0-9]+.?){4}" -o|head -n 1
206.190.238.90
awk
[root@famous-machine-1 ~]# ip a s eth0|awk -F"[ /]+" 'NR==3{print $3}'
206.190.238.90
sed
[root@famous-machine-1 ~]# ip a s eth0|sed -rn 's#.*net (.*)/22.*#1#gp'
206.190.238.90