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
1.0k views
in Technique[技术] by (71.8m points)

regex - Extracting IP address from a line from ifconfig output with grep

Given this specific line pulled from ifconfig, in my case:

inet 192.168.2.13 netmask 0xffffff00 broadcast 192.168.2.255

How could one extract the 192.168.2.13 part (the local IP address), presumably with regex?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Here's one way using grep:

line='inet 192.168.2.13 netmask 0xffffff00 broadcast 192.168.2.256'

echo "$line" | grep -oE "([0-9]{1,3}.){3}[0-9]{1,3}"

Results:

192.168.2.13
192.168.2.256

If you wish to select only valid addresses, you can use:

line='inet 192.168.0.255 netmask 0xffffff00 broadcast 192.168.2.256'

echo "$line" | grep -oE "((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"

Results:

192.168.0.255

Otherwise, just select the fields you want using awk, for example:

line='inet 192.168.0.255 netmask 0xffffff00 broadcast 192.168.2.256'

echo "$line" | awk -v OFS="
" '{ print $2, $NF }'

Results:

192.168.0.255
192.168.2.256


Addendum:

Word boundaries:


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

...