-1

In Ubuntu 16.04 I ran ifconfig and saw my external ip as in inet addr:MY_IP.

I tried to "dug" it right into a variable in these ways:

ipa=$(ifconfig | grep "inet addr:\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b")

and:

ipa=$(ifconfig | grep "inet addr:\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.")

These methods work:

ipa=$(ifconfig | grep -Po 'inet addr:\K[^\s]+' | grep -v '^127')

and

ipa=$(ifconfig | grep -A 1 eth0 | grep -Po "inet addr:(\d{1,3}\.){3}\d{1,3}" | cut -f2 -d:)

But I would like to know, please, what I've missed in my first 2 tryings.

Update:

Is there a way to use one grep with 4 groups (similar to the concept of the first 2) that will indeed work in POSIX BRE?

Osi
  • 1
  • 3
  • 9
  • 30
  • 2
    POSIX BRE used in the first case does not support `\b` and `\d`, and `{...}` must be escaped. The seocnd one contains unescaped `(` and `)` and non-supported `\b` and only matches one octet. – Wiktor Stribiżew Dec 12 '17 at 20:27
  • @WiktorStribiżew I swear your comment was posted before the question. – ctwheels Dec 12 '17 at 20:28
  • @ctwheels POSIX BRE does not support `\K`. The third one is a PCRE regex. – Wiktor Stribiżew Dec 12 '17 at 20:30
  • @WiktorStribiżew my bad, failed to see `P` – ctwheels Dec 12 '17 at 20:30
  • Even with `grep -E` first 2 commands won't work because it will match complete line instead of extracting IP address – anubhava Dec 12 '17 at 20:31
  • Is there a way to use one `grep` with 4 groups (similar to the concept of the first 2) that will indeed work in POSIX BRE? – Osi Dec 12 '17 at 20:39
  • If you want to get internal IP then use `ip route get 4.4.4.4 | awk '{print $NF; exit}'` – anubhava Dec 12 '17 at 20:57
  • Possible duplicate of [Which terminal command to get just IP address and nothing else?](https://stackoverflow.com/questions/8529181/which-terminal-command-to-get-just-ip-address-and-nothing-else) – marcell Dec 12 '17 at 22:04

1 Answers1

1

You can replace \b with the old-style \< though it doesn't seem to be POSIX.

Notice also that alternation (a|b) is a grep -E feature. In POSIX grep, you can backslash those constructs (weirdly) but I'd just go with grep -E.

ipa=$(ifconfig | grep -E "inet addr:\<(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.")

There is no need for a word boundary there, though; you already know the character to the left is a colon and the one to the right is a digit.

tripleee
  • 175,061
  • 34
  • 275
  • 318