1.sed取ip地址
①传统写法
[root@localhost cs]# ifconfig eth0 | sed -n '2p'
inet addr:192.168.197.150 Bcast:192.168.197.255 Mask:255.255.255.0
[root@localhost cs]# ifconfig eth0 | sed -n '2p'|sed 's/^.*dr://g'
192.168.197.150 Bcast:192.168.197.255 Mask:255.255.255.0
[root@localhost cs]# ifconfig eth0 | sed -n '2p'|sed 's/^.*dr://g'|sed 's/ Bcast.*$//g'
192.168.197.150
[root@localhost cs]#
②
sed -rn :
-r代表拓展正则,后面不需要转义字符 \ 来对有歧义的特殊符号进行转义,后面可以接拓展正则表达式
-n 取消默认输出
^.dr以任意字符开头匹配到dr结束
Bcast.$ 以Bcast起始一直到最后结束
\1 固定写法,代表(.*)的内容
[root@localhost cs]# ifconfig|sed -rn 's/^.*dr:(.*) Bcast.*$/\1/gp'
192.168.197.150
[root@localhost cs]#
③利用ifconfig eth0|sed -n '/inet addr:19/p’过滤出来这一行,然后再用/s###g/进行替换
[root@localhost ~]# ifconfig eth0
eth0 Link encap:Ethernet HWaddr 00:0C:29:7C:5B:79
inet addr:192.168.197.150 Bcast:192.168.197.255 Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fe7c:5b79/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:87822 errors:0 dropped:0 overruns:0 frame:0
TX packets:63769 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:72874461 (69.4 MiB) TX bytes:27158178 (25.9 MiB)
[root@localhost ~]# ifconfig eth0|sed -nr '/inet addr:19/s#^.*:(.*) Bca.*$#\1#p'
192.168.197.150
[root@localhost ~]#
2.awk
注意:print外面的’{ }’ 必须存在
[root@localhost ~]# ifconfig eth0
eth0 Link encap:Ethernet HWaddr 00:0C:29:7C:5B:79
inet addr:192.168.197.150 Bcast:192.168.197.255 Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fe7c:5b79/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:87353 errors:0 dropped:0 overruns:0 frame:0
TX packets:63516 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:72824853 (69.4 MiB) TX bytes:27110624 (25.8 MiB)
[root@localhost ~]# ifconfig eth0| awk -F '[:]' 'NR==2{print$2}'|awk -F'[ ]' '{print$1}'
192.168.197.150
[root@localhost ~]# ifconfig eth0| awk -F '[ :]+' 'NR==2{print$4}'
192.168.197.150