简体   繁体   中英

How can I select the IP address from the output of the `ip route` command?

$ ip route get 255.255.255.255

broadcast 255.255.255.255 dev eth0 src 192.168.223.129

I want to get the IP address of 192.168.223.129 all I know is that I have to use the sed command. Also, can you please describe the command used?

if I would extract text, the first thing comes up is grep/ack.

try this:

ip route get 255.255.255.255|grep -oP '(?<=src ).*'

This a pattern matching problem which grep is simplest and most suited tool to do this.

What you are looking to match is an IP address following the word src . You can you use this regex to match an IP address: (\\d{1,3}.){4} and use positive lookbehind to make sure the IP address follows the word src like (?<=src ) :

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

To use positive lookahead with grep you need to use the -P flag for perl regular expressions and the -o flag tells grep to only display the matching part of the line as the default behaviour of grep is to display the whole line that contains a match.

This solution is independent of the output from ip route get 255.255.255.255 as you are searching for and IP address following the word src and not relying on the format of the output such as it happening to be the last word on the first line.

Use AWK Instead

This problem is easier to solve with AWK. Assuming it's not a homework assignment, use the right tool for the job! For example, to store the IP address in a variable for later use, you can do the following:

ip_address=$(
    ip route get 255.255.255.255 |
    awk '{print $NF; exit}'
)

You can then access the value through the your new variable. For example:

$ echo "$ip_address"
192.168.1.1

If you can do with out sed , here is something that will work : Output of ip route

[aman@aman ~]$ ip route get 255.255.255.255
broadcast 255.255.255.255 dev wlan0  src 192.168.1.4 
    cache <local,brd> 

Getting the ip address

[aman@aman ~]$ ip route get 255.255.255.255|head -1|cut -f7 -d' '
192.168.1.4

With sed you could do it like this:

ip route get 255.255.255.255 | sed -n '/src/ s/.*src //p'

-n suppresses output. The /src/ bit selects which lines to perform the substitute s/// and print p command on. The substitute command s/.*src // removes everything up to and including src (notice the trailing space).

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