使用grep从ifconfig输出中的行中提取IP地址 [英] Extracting IP address from a line from ifconfig output with grep

查看:1068
本文介绍了使用grep从ifconfig输出中的行中提取IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ifconfig 取出这个特定的行,在我的情况中:

inet 192.168.2.13 netmask 0xffffff00 broadcast 192.168.2.255



如何提取 192.168.2.13 部分(本地IP地址),大概是用正则表达式吗?

解决方案

c> grep :

  line ='inet 192.168.2.13 netmask 0xffffff00 broadcast 192.168 .2.256'

echo$ line| grep -oE\b([0-9] {1,3} \。){3} [0-9] {1,3} \b



结果:

  192.168.2.13 
192.168.2.256






如果您愿意要选择只有有效的地址,你可以使用:

  line ='inet 192.168.0.255 netmask 0xffffff00 broadcast 192.168。 2.256'

echo$ line| grep -oE\b((25 [0-5] | 2 [0-4] [0-9] | [01]?[0-9] [0-9]?)\。){3 }(25 [0-5] | 2 [0-4] [0-9] | [01]?[0-9] [0-9]?)\ b​​
  192.168.0.255 






否则,只需选择您想要的字段使用 awk ,例如:
$ b

  line =' inet 192.168.0.255 netmask 0xffffff00 broadcast 192.168.2.256'

echo$ line| awk -v OFS =\ n'{print $ 2,$ NF}'

结果:

  192.168.0.255 
192.168.2.256









附录:

词界 \b


Given this specific line pulled from ifconfig, in my case:

inet 192.168.2.13 netmask 0xffffff00 broadcast 192.168.2.255

How could one extract the 192.168.2.13 part (the local IP address), presumably with regex?

解决方案

Here's one way using grep:

line='inet 192.168.2.13 netmask 0xffffff00 broadcast 192.168.2.256'

echo "$line" | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b"

Results:

192.168.2.13
192.168.2.256


If you wish to select only valid addresses, you can use:

line='inet 192.168.0.255 netmask 0xffffff00 broadcast 192.168.2.256'

echo "$line" | grep -oE "\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"

Results:

192.168.0.255


Otherwise, just select the fields you want using awk, for example:

line='inet 192.168.0.255 netmask 0xffffff00 broadcast 192.168.2.256'

echo "$line" | awk -v OFS="\n" '{ print $2, $NF }'

Results:

192.168.0.255
192.168.2.256



Addendum:

Word boundaries: \b

这篇关于使用grep从ifconfig输出中的行中提取IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆