Regex for inet addr failed

南笙酒味 提交于 2019-12-11 15:52:04

问题


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?


回答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.



来源:https://stackoverflow.com/questions/47780979/regex-for-inet-addr-failed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!