Linux中过滤IP地址的9种方法i

回复 收藏

    有时候我们写脚本经常要利用本机IP地址,下面是我网上收集后归纳出的9种方法,仅供大家参考参考。

[root@localhost ~]# ifconfig
eth0      Link encap:Ethernet  HWaddr DA:DE:BE:41:89:18
          inet addr:192.168.150.53  Bcast:192.168.150.255  Mask:255.255.255.0
          inet6 addr: fe80::d8de:beff:fe41:8918/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:184255445 errors:0 dropped:0 overruns:0 frame:0
          TX packets:51947 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:12701252470 (11.8 GiB)  TX bytes:4422271 (4.2 MiB)
          Interrupt:17


方法1:匹配 inet addr 这行;以冒号为分隔符,显示第2段;再次以空格为分隔符,显示第1段
[root@localhost ~]# ifconfig eth0 |grep 'inet addr' |cut -d: -f2 |cut -d" " -f1
192.168.150.53

方法2:匹配 inet addr 这行;以空替换从开头到 addr: 的字符串;再次以空替换从Bcast到结尾的字符串
[root@localhost ~]# ifconfig eth0 |grep 'inet addr' |sed 's/^.*addr://g' |sed 's/Bcast.*$//g'
192.168.150.53

方法3:匹配 inet addr 这行;以:或者空格作为分隔符,然后打印第4列
[root@localhost ~]# ifconfig eth0 |grep 'inet addr' |awk -F[:" "]+ '{print $4}'
192.168.150.53

方法4:匹配 inet addr 这行;以:作为分隔符,打印第2列,然后再打印第一列
[root@localhost ~]# ifconfig eth0 |grep 'inet addr' |awk -F: '{print $2}' |awk '{print $1}'
192.168.150.53

方法5:
[root@localhost ~]# ifconfig eth0|sed -nr '2s#^.*addr:(.*) Bcast.*$#\1#g'p
192.168.150.53

方法6:
[root@localhost ~]# ifconfig eth0 |awk '/inet addr:/ {print $2}' |awk -F: '{print $2}'
192.168.150.53

方法7:
[root@localhost ~]# ifconfig eth0 |awk '/inet addr:/ {print $2}' |awk -F: '{print $2}'
192.168.150.53

方法8:
[root@localhost ~]# ifconfig eth0 |awk 'NR==2 {print $2}' |awk -F: '{print $2}'
192.168.150.53

方法9:
[root@localhost ~]# ip add |awk -F '[ /]+' 'NR==8 {print $3}'
192.168.150.53


欢迎大家来我的51cto博客一起分享探讨Linux知识:http://msiyuetian.blog.51cto.com/




2016-01-19 13:04 举报
已邀请:
0

soul

赞同来自:

果然涨知识
0

weifan

赞同来自:

666

回复帖子,请先登录注册

退出全屏模式 全屏模式 回复
评分
可选评分理由: