3

I'm trying to extract the IPv4 address of a network interface on Linux. I have a working solution:

IFACE=eth0
ip a show dev $IFACE | sed -n 's/.*inet \(.*\)\/.*/\1/p'

For the record, here is a sample output of the ip a show command:

2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:51:51:b4:a9:08 brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.20/24 brd 10.0.2.255 scope global ens192
       valid_lft forever preferred_lft forever
    inet6 fe80::251:56ff:fec1:4915/64 scope link 
       valid_lft forever preferred_lft forever

While my solution works, I'm wondering if there is a sed way to grab the content of the regex pattern match group and replace the current line (in sed terms, the pattern space) with it or print it somehow? I consider having to use s///p and expanding the pattern to the whole line (with .* at the beginning and the end) to be a kludge.

2 Answers 2

5

Parsing ip human-oriented output is a kludge. Use the JSON output:

ip -4 -json a show dev $IFACE scope global | jq -r ".[].addr_info[].local"
2
  • That's a good idea, but "jq" is usually not present on the machines. Also your solution prints a couple of extra "null" lines. My question is more about sed.
    – neuhaus
    Feb 3, 2023 at 11:37
  • Using jq -r '..|.local?|select( . != null)' gets rid of the nulllines.
    – neuhaus
    Feb 3, 2023 at 11:46
2

You could remove everything you don't want, e.g.: sed -n 's:.*inet ::; T; s:/.*::p'.

However, another approach is to use ip -o -f inet and standard tools, e.g. with tr and cut:

ip -o -f inet addr show dev eth0 | tr -s ' ' '/' | cut -d/ -f4
2
  • I appreciate the different suggestions however i specifially asked for a different way to do it with sed. So it's more of a sed question.
    – neuhaus
    Feb 8, 2023 at 16:43
  • @neuhaus: sed -n 's:.*inet ::; T; s:/.*::p' is different
    – Thor
    Feb 8, 2023 at 22:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .