简体   繁体   中英

bash script - sed to return ip address

I'm developing a bash script and I'm trying to get an IPv4 address from a network interface that is ON, on this operation I'm using ip addr and sed , but something is wrong because I can't get IP from sed .

So, the script at some point have this:

ip addr show dev eth0 | grep "inet "

This supposedly returns:

inet 192.168.1.3/24 brd 192.168.1.255 scope global eth0

And with sed , I want this:

192.168.1.3/24

I have tried some regular expressions, but it only gives error or blank lines! How can I achieve this?

Try this

ip addr show dev eth0 | sed -nr 's/.*inet ([^ ]+).*/\1/p'

EDIT: Explanatory words as requested.

-n in sed suppressed automatic printing of input line
-r turns on extended regular expressions




s/.*inet ([^ ]+).*/\1/p

Search for a anything followed by inet and a space, remember everything [that's the parentheses] that's not a space AFTER that space, followed by anything, and replace everything with the remembered thing [\\1] (the IP address), and then print that line (p).

I know you asked for sed, so here's an answer that works using GNU sed version 4.2.1. It's really specific, and very overbaked for what you need. Based on your ip addr show command, I assume this is a Linux.

ip addr show dev eth0 \
  | sed -n '/^\s\+inet\s\+/s/^\s\+inet\s\+\(.*\)\s\+brd\s.*$/\1/p'`

An easier way using awk:

ip addr show dev eth0 | awk '$1=="inet" {print $2}'

你可以使用这样的东西:

sed -e 's/^[^ ]* //' -e 's/ .*//'

使用grep直接找到你的答案。

ip addr show dev eth0 | grep -P '\d+\.\d+\.\d+.\d+\/\d+' -o

Well, both of the answers with sed and awk are quite good. In order to just get only the IP without the subnet mask, you could proceed further just like this:

ip addr show dev eth0 | sed -nr 's/.*inet ([^ ]+).*/\1/p' **| cut -f1 -d'/'**

or

ip addr show dev eth0 | awk '$1=="inet" {print $2}' **| cut -f1 -d'/'**

or

Even better:

ip route get 255.255.255.255 | grep -Po '(?<=src )(\d{1,3}.){4}'

This should output only the IP Address.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM