如何利用sed取ip地址

 

考题:取ifocnfig eth0 的ip地址

目标:192.168.1.200

[root@NFS ~]# ifconfig eth0

eth0????? Link encap:Ethernet? HWaddr 00:50:56:33:66:20

????????? inet addr:192.168.1.200? Bcast:192.168.1.255? Mask:255.255.255.0

????????? inet6 addr: fe80::250:56ff:fe33:6620/64 Scope:Link

????????? UP BROADCAST RUNNING MULTICAST? MTU:1500? Metric:1

?? ???????RX packets:62 errors:0 dropped:0 overruns:0 frame:0

????????? TX packets:59 errors:0 dropped:0 overruns:0 carrier:0

????????? collisions:0 txqueuelen:1000

????????? RX bytes:7676 (7.4 KiB)? TX bytes:7967 (7.7 KiB)

过滤思想:

目标之前的内容“???????? inet addr:” 就用 ^.*addr:

目标结尾的内容”? Bcast:10.0.0.255? Mask:255.255.255.0? “就用Bc.*$

解题过程:

#打印ip地址所在的行

[root@NFS ~]# ifconfig eth0|sed -n ‘2p’

????????? inet addr:192.168.1.200? Bcast:192.168.1.255? Mask:255.255.255.0

#将以inet addr:开头的内容替换为空,即过滤掉

[root@NFS ~]# ifconfig eth0|sed -n ‘2s/^.*addr://gp’

192.168.1.200? Bcast:192.168.1.255? Mask:255.255.255.0

#将以Bcast:10.0.0.255? Mask:255.255.255.0结尾的内容替换为空,即过滤掉

[root@NFS ~]# ifconfig eth0|sed -n ‘2p’|sed ‘s/Bc.*$//g’

????????? inet addr:192.168.1.200

#将前2个命令组合一下,就OK了

[root@NFS ~]# ifconfig eth0|sed -n ‘2s/^.*addr://gp’|sed ‘s/Bc.*$//g’????

192.168.1.200

QQ20150424163922

 

其他方法取ip地址,可以用cut实现

[teddylu@Web-02 ~]$ ifconfig eth0|grep ‘inet addr’|cut -d: -f2|cut -d” ” -f1
192.168.1.204

cut参数说明

-d, –delimiter=DELIM
use DELIM instead of TAB for field delimiter ??指定分隔符

-f, –fields=LIST
select only these fields; also print any line that contains no delimiter character, unless the -s option is specified ? ? ? ? ? ? ?指定输出的域

解题的思路:

[teddylu@Web-02 ~]$ ifconfig eth0
eth0 Link encap:Ethernet HWaddr 00:0C:29:D7:0C:6D
inet addr:192.168.1.204 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fed7:c6d/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:1866319 errors:0 dropped:0 overruns:0 frame:0
TX packets:136224 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:2761798157 (2.5 GiB) TX bytes:15149581 (14.4 MiB)

[teddylu@Web-02 ~]$ /sbin/ifconfig eth1|grep ‘inet addr’
inet addr:10.0.0.204 Bcast:10.0.0.255 Mask:255.255.255.0
[teddylu@Web-02 ~]$ ifconfig eth0|grep ‘inet addr’|cut -d: -f2
192.168.1.204 Bcast
[teddylu@Web-02 ~]$ ifconfig eth0|grep ‘inet addr’|cut -d: -f2|cut -d” ” -f1
192.168.1.204

 

此条目发表在未分类分类目录。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。 必填项已用*标注