I'm trying to get just the local IP of my Arch VM. I've managed to get just the line containing what I want with grep, but I also want to trim it down with sed.

inet <<>>/24 brd 192.1680.255 scope global enp0s3 $ I want the IP in <<>>
ip addr show | grep 'inet\ ' | sed -n -e 's/^.*inet\ (.*)\/.*$/\1/p'
-n     # print nothing by default
s      # replacement command
^      # begin line
.*     # anything
inet\  # inet and then a space
(.*)   # capture anything
\/     # end capture at the / that comes before 24
.*     # anything
$      # end
\1     # replace all that with the first capture group which should be the IP
p      # print the output

But as soon as I add the sed, it gives me nothing. I assume something is wrong with my regex.

  • @don_crissti Oh right! Thanks, I forgot about that. That actually fixes my problem. Sorry for the bad information.
    – Rogue
    Nov 28 '15 at 21:52

This is easier to do with awk than grep and sed:

ip addr show eth0 | awk '/inet / {print $2}'

If you want to strip the CIDR netmask from the IP:

ip addr show eth0 | awk '/inet / {gsub(/\/.*/,"",$2); print $2}'

Note that an interface may have more than one IP address - e.g. ip addr show br0 | awk '/inet / {print $2}' on my system has 11 IPv4 addresses, some of them being public IP addresses and some of them RFC1918 private addresses.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.