使用 grep 从 ifconfig 输出的一行中提取 IP 地址 [英] Extracting IP address from a line from ifconfig output with grep
本文介绍了使用 grep 从 ifconfig 输出的一行中提取 IP 地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
鉴于从 ifconfig
中提取的特定行,在我的情况下:
Given this specific line pulled from ifconfig
, in my case:
inet 192.168.2.13 网络掩码 0xffffff00 广播 192.168.2.255
如何提取 192.168.2.13
部分(本地 IP 地址),大概是使用正则表达式?
How could one extract the 192.168.2.13
part (the local IP address), presumably with regex?
推荐答案
这是使用 grep
的一种方法:
Here's one way using grep
:
line='inet 192.168.2.13 netmask 0xffffff00 broadcast 192.168.2.256'
echo "$line" | grep -oE "([0-9]{1,3}.){3}[0-9]{1,3}"
结果:
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 "((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]?)"
结果:
192.168.0.255
<小时>
否则,只需使用awk
选择您想要的字段,例如:
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="
" '{ print $2, $NF }'
结果:
192.168.0.255
192.168.2.256
<小时><小时>
附录:
Addendum:
词边界:
这篇关于使用 grep 从 ifconfig 输出的一行中提取 IP 地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文