Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

linux - Regex for inet addr failed

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:d{1,3}.d{1,3}.d{1,3}.d{1,3}")

and:

ipa=$(ifconfig | grep "inet addr:(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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can replace 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...