5

I thought getting an IP address on OSX or Linux would be rather easy to learn how to use regular expression with grep, but it looks like I either have a syntax error or misunderstanding of what is required.

I know this regex is correct, although I know it may not be a valid IP address I'm not considering that at this point.

(\d{1,3}\.){3}\d{1,3}

so I'm not sure why this doesn't work.

ifconfig | grep -e "(\d{1,3}\.){3}\d{1,3}"
Sn3akyP3t3
  • 656
  • 4
  • 10
  • 23

2 Answers2

5

Two things:

First, there is a difference between -e and -E : -e just says "the next thing is an expression", while -E says: "use extended regular expressions". Depending on the exact version of grep you are using, you need -E to get things to work properly.

Second, as was pointed out before, -d isn't recognized by all versions of grep. I found that the following worked: since ip addresses are "conventional" numbers, we don't need anything more fancy than [0-9] to find them:

ifconfig | grep -E '([0-9]{1,3}\.){3}[0-9]{1,3}'

No need to escape other characters (in my version of grep - using OSX 10.7.5)

Incidentally, when testing your regular expression you can consider using something like

echo "10.1.15.123" | grep -E '([0-9]{1,3}\.){3}[0-9]{1,3}'

to confirm that your regex is working - regardless of the exact output of ifconfig. It breaks the problem into two smaller problems, which is usually a good strategy.

Floris
  • 45,857
  • 6
  • 70
  • 122
  • Can the matching group in the regex alone be printed? – kvn Sep 01 '16 at 14:51
  • @SGSVenkatesh please see [this question](http://stackoverflow.com/q/1546711/1967396) and associated answers. If that doesn't suffice, consider asking a more specific question. – Floris Sep 01 '16 at 14:56
0

\d is not understood by grep, instead you could use [0-9] or [[:digit:]]. Unfortunately there are many dialects of regular expressions. You will also have to escape {, }, ( and ). The following works for me

/sbin/ifconfig | grep -e "\([[:digit:]]\{1,3\}\.\)\{3\}[[:digit:]]\{1,3\}"
Bryan Olivier
  • 5,207
  • 2
  • 16
  • 18