正则实践

1.通过awk获取IP地址
[root@localhost ~]# ifconfig eth2 | grep inet
                    inet addr:10.3.151.25  Bcast:10.3.151.255  Mask:255.255.255.0
                    inet6 addr: fe80::250:56ff:fe80:6e7e/64 Scope:Link
[root@localhost ~]# ifconfig eth2 | grep "\binet\b"
                    inet addr:10.3.151.25  Bcast:10.3.151.255  Mask:255.255.255.0
[root@localhost ~]# ifconfig eth2 | grep "\binet\b" | awk '{print $0}'
                    inet addr:10.3.151.25  Bcast:10.3.151.255  Mask:255.255.255.0
[root@localhost ~]# ifconfig eth2 | grep "\binet\b" | awk '{print $2}'
addr:10.3.151.25
[root@localhost ~]# ifconfig eth2 | grep "\binet\b" | awk '{print $2}'| awk -F ':' '{print $2}'
10.3.151.25

[root@localhost ~]# ifconfig  eth2 | awk -F '[ :]+' 'NR==2 {print $4}'
10.3.151.25

2.通过sed获取IP地址
[root@localhost ~]# ifconfig eth2 | sed -n '2p'
                    inet addr:10.3.151.25  Bcast:10.3.151.255  Mask:255.255.255.0
[root@localhost ~]# ifconfig eth2 | sed -n '2p' | sed 's#^.*dr:##g'
10.3.151.25  Bcast:10.3.151.255  Mask:255.255.255.0
[root@localhost ~]# ifconfig eth2 | sed -n '2p' | sed 's#^.*dr:##g' | sed 's#  B.*##g'
10.3.151.25

3.通过sed后向引用
sed -n 's#()()#\1\2#g' file
当在前面匹配部分用小短号的时候,第一个括号的内容,可以在后面引用\1输出
第二个括号的内容,可以在后面引用\2输出

例子:
my name is Mingkang how are you。
[root@localhost ~]# cat test.txt | sed -nr 's#^.*s (.*) h.*$#\1#gp'
Mingkang                 #要求直接输入Mingkang

[root@localhost ~]# ifconfig eth2
eth2      Link encap:Ethernet  HWaddr 00:50:56:80:6E:7E  
                    inet addr:10.3.151.25  Bcast:10.3.151.255  Mask:255.255.255.0
                    inet6 addr: fe80::250:56ff:fe80:6e7e/64 Scope:Link
                    UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
                    RX packets:2223593069 errors:0 dropped:0 overruns:0 frame:0
                    TX packets:2229351853 errors:0 dropped:0 overruns:0 carrier:0
                    collisions:0 txqueuelen:1000 
                    RX bytes:163251461945 (152.0 GiB)  TX bytes:131281217921 (122.2 GiB)

[root@localhost ~]# ifconfig eth2 | sed -nr 's#^.*dr:(.*)  B.*$#\1#gp'
10.3.151.25