Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 使用grep提取IP地址的正则表达式_Regex_Bash - Fatal编程技术网

Regex 使用grep提取IP地址的正则表达式

Regex 使用grep提取IP地址的正则表达式,regex,bash,Regex,Bash,我正在尝试解析默认路由的默认IP地址 我已经有了默认路由,我正在尝试从中提取IP地址 /sbin/ip addr show dev eth0 | grep 'inet' 获取IP地址所在的正确行: inet 10.1.4.33/22 brd 10.1.83.255 scope global eth0 我需要帮助提取IP地址第10.1.4.33部分将您的输出传输到grep-o: /sbin/ip addr show dev eth0 | grep'inet | grep-oE“([0-9]{1

我正在尝试解析默认路由的默认IP地址

我已经有了默认路由,我正在尝试从中提取IP地址

/sbin/ip addr show dev eth0 | grep 'inet'
获取IP地址所在的正确行:

inet 10.1.4.33/22 brd 10.1.83.255 scope global eth0

我需要帮助提取IP地址第10.1.4.33部分将您的输出传输到
grep-o

/sbin/ip addr show dev eth0 | grep'inet | grep-oE“([0-9]{1,3}”){3}[0-9]{1,3}”| head-n1


只需使用
头-n 1
来选择第一个匹配项。

您可以使用此
awk

/sbin/ip addr show dev eth0 | awk -F '[ /\t]+' '$2=="inet"{print $3; exit}'
192.168.0.52

在awk中也尝试一种方法

/sbin/ip addr show dev eth0 | awk '{match($0,/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/);if(substr($0,RSTART,RLENGTH) && $0 ~ /inet/){print substr($0,RSTART,RLENGTH)}}'

要完成可用选项,请使用sed:

ip add show dev eth0 | sed -rn 's@^.*inet[[:blank:]]([[:digit:]]{1,3}(.[[:digit:]]{1,3}){3})/.*$@\1@p'

不需要复杂的正则表达式

output=$(/sbin/ip addr show dev eth0 | grep 'inet')
[[ $output = inet\ (.*)/ ]] && ip_addr=${BASH_REMATCH[1]}

它涉及两个
grep
和一个
head
调用,所有这些都可以在一个
awk
中完成。