Reputation: 21
I'm trying to get the machine's ipv4 address. I've got this working but is there a way to specify you want index 2 from the returned data?
ip a | grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}"
Output
127.0.0.1
192.168.13.131
192.168.13.255
Upvotes: 2
Views: 724
Reputation: 163362
One option is to pipe it to sed and print the second line
ip a | grep -Eo "([0-9]{1,3}\.){3}[0-9]{1,3}" | sed -n 2p
Another option could be using a combination of head and tail, showing the first n items with head and then take the last item from that result.
ip a | grep -Eo "([0-9]{1,3}\.){3}[0-9]{1,3}" | head -n2 | tail -n1
If -P
is supported for pcre, you might also use a longer pattern, repeating matching the ip number n times using a quantifier, for example {2}
for repeating 2 times.
Then use \K
to clear the match buffer and output only the ip number of interest.
ip a | grep -Poz "(?s)\A(?:.*?(?:[0-9]{1,3}\.){3}[0-9]{1,3}){2}.*?\K(?:[0-9]{1,3}\.){3}[0-9]{1,3}"
^^^ quantifier
Upvotes: 3
Reputation: 133518
With awk
, please try following, written as per your attempt.
ip a |
awk '
match($0,/([0-9]{1,3}\.){3}[0-9]{1,3}/) && ++count==2{
print substr($0,RSTART,RLENGTH)
}'
Explanation: Adding detailed explanation for above solution.
ip a |
##Running ip a command and sending its output to awk as input
awk '
##Starting awk program from here.
match($0,/([0-9]{1,3}\.){3}[0-9]{1,3}/) && ++count==2{
##Using match function to match IP address and checking if its 2nd time coming.
print substr($0,RSTART,RLENGTH)
##Printing matching sub string here.
}'
Upvotes: 3