Bash script - sed to return ip address

I am developing a bash script and I am trying to get the IPv4 address from the network interface that is included, in this operation I use ip addr and sed , but something is wrong because I can not get the IP from sed .

So the script at some point has 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 tried some regular expressions, but it gives only errors or empty lines! How can I achieve this?

+4
source share
5 answers

try it

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

EDIT: Explanatory words on request.

 -n in sed suppressed automatic printing of input line -r turns on extended regular expressions s/.*inet ([^ ]+).*/\1/p 

Find something followed by inet and a space, remember everything [in brackets] that there is no space AFTER this space, followed by something, and replace everything with a memorable thing [\ 1] (IP address), and then print this line (p).

+2
source

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

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

A simpler way to use awk:

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

+1
source

You can use something like this:

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

Use grep to directly find out your answer.

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

Well, both answers with sed and awk are pretty good. To just get only IP without a subnet mask, you can go on 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 only output the IP address.

0
source

All Articles