get IP address using sed

It is possible to accomplish this task several ways.
Maybe, you know a faster/better way to do that, in that case, I would appreciate if you email-me your solution !
Here are 2 ways with sed, replace/adapt to fit your needs :

  • imitating ‘cut’ and ‘grep’ with one sed thread :
    ifconfig eth0 | sed -n ‘s/\(^ *inet ad\{1,2\}r:\)\(\([0-9]\{1,3\}.\)\{3\}[0-9]\{1,3\}\)\( *.*$\)/\2/p’

    This command “grep” the line starting with the keyword ‘inet’ and then “cut” it into 3 parts and then only keep the 2nd part (which is the ip address).

    # -n option prevents sed to display the whole output of ifconfig
    # p command at the end print the output we want
  • recursive sed syntax :
    ifconfig eth0 | sed -n ‘/inet ad/{s/^ *inet ad\{1,2\}r://;s/ .*//;p}’

P.S. : I use ‘ad\{1,2\}r’, because I noticed that on Debian (maybe only French versions), it is ‘adr’ and on other distros ‘addr.


update : Another way is to use -r switch from sed (—regexp-extended).
With that option, it’s not required to escape special characters.

This one shows every IP (except 127.0.01) on my system :

ifconfig | sed -rn ‘s/(^ *inet ad{1,2}r:)(([0-9]{1,3}.){3}[0-9]{1,3})( *.*cast.*$)/\2/p’