I am trying to parse the default IP address of the default route.
I already have the default route and I'm trying to extract the IP address from it.
/sbin/ip addr show dev eth0 | grep 'inet'
Gets me as far as the correct line where the IP address is:
inet 10.1.4.33/22 brd 10.1.83.255 scope global eth0
And I need help extracting the IP address part 10.1.4.33
Pipe your output to grep -o
:
/sbin/ip addr show dev eth0 | grep 'inet' | grep -oE "([0-9]{1,3}\\.){3}[0-9]{1,3}" | head -n 1
The head -n 1
is required to select the first match only.
You can use this 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'
No complicated regular expression is needed.
output=$(/sbin/ip addr show dev eth0 | grep 'inet')
[[ $output = inet\ (.*)/ ]] && ip_addr=${BASH_REMATCH[1]}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.