[英]Trying to capture IP address from `ifconfig` in terminal
I'm trying to come up with a quick command in order to get the IP address of a computer via grep
and the ifconfig
command. 我正在尝试提出一个快速命令,以便通过grep
和ifconfig
命令获取计算机的IP地址。
So far, I have this ifconfig eth0 | grep -Eo 'inet addr:[0-9\\.]+'
到目前为止,我有这个ifconfig eth0 | grep -Eo 'inet addr:[0-9\\.]+'
ifconfig eth0 | grep -Eo 'inet addr:[0-9\\.]+'
which will return: ifconfig eth0 | grep -Eo 'inet addr:[0-9\\.]+'
将返回:
inet addr:192.168.1.26
I'm trying to adjust the regex though so that I only get the IP address itself. 我正在尝试调整正则表达式,以便仅获取IP地址本身。 I have very limited knowledge of regex, and I put a non-capturing group around 'inet addr:' which made the command look like this: 我对正则表达式的了解非常有限,我在'inet addr:'周围放置了一个非捕获组,这使命令看起来像这样:
ifconfig eth0 | grep -Eo '(?:inet addr:)[0-9\\.]+'
but that still didn't solve my issue. 但这仍然不能解决我的问题。
You can use: 您可以使用:
ifconfig | awk '$1=="inet" && $2!="127.0.0.1"{print $2}'
Or on Linux: 或在Linux上:
ifconfig eth0 | awk -F '[ :]+' '$2=="inet" {print $4}'
You can use cut
, to cut output into substrings by delimiter :
. 您可以使用cut
,通过定界符将输出切为子字符串:
ifconfig eth0 | grep -Eo 'inet addr:[0-9\.]+' | cut -d':' -f 2
Flag -f 2
is used to select second substring. 标志-f 2
用于选择第二个子字符串。
Use a lookbehind expression; 使用后向表达式; with grep
, you need to add the -P
switch to enable this construct instead of -E
(at least under bash v4.1.1 for cygwin). 使用grep
,您需要添加-P
开关以启用此构造,而不是-E
(至少在cygwin的bash v4.1.1下)。 And so just change a little your last try: 因此,只需稍作更改即可:
ifconfig eth0 | grep -Po '(?<=inet addr:)[0-9\.]+'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.