Reputation: 6890
$ 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?
Upvotes: 1
Views: 2607
Reputation: 85875
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.
Upvotes: 4
Reputation: 84423
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
Upvotes: 2
Reputation: 195209
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 ).*'
Upvotes: 3
Reputation: 47189
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).
Upvotes: 1
Reputation: 8995
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
Upvotes: 1