开发者

Filter out IP using regex and sed

开发者 https://www.devze.com 2023-02-13 09:53 出处:网络
I\'m having real trouble converting my regular expression into a working sed command on Centos 5.5. I want to filter the IP address out of a string:

I'm having real trouble converting my regular expression into a working sed command on Centos 5.5.

I want to filter the IP address out of a string:

"example.org has address 123.45.67.890" -> "123.45.67.890"

My regular expression so far is:

/([a-zA-Z\. ]+)([0-9\.]+)/

And an example of my command开发者_如何学Python using sed is:

host example.org | grep 'has address' | sed 's/\([a-zA-Z\\. ]+\)\([0-9\\.]+\)/\2/'

But all I get back from that command is the input to sed: "example.org has address 123.45.67.890"

Any ideas?


host example.org | awk '/has address/ {print $4 }'


Here's a very simple way to do it without a regex:

host example.org | grep "has addres" | awk '{print $4}'


You don't really need sed for this. You could use cut instead to parse the spaces:

host example.org | grep 'has address' | cut -d' ' -f4

This just takes the 4th word, when delimited by spaces.


Your ([a-zA-Z\. ]+) captures everything before the IP address and includes that in the match. It will also cause matching to fail if the domain name has any numbers in it. Use a lookbehind:

/(?<has address )\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/

You apparently need to use Perl mode for sed to support lookbehinds. You could also use capture groups. If you want a more discriminating pattern (i.e. only match stuff that looks very strongly like an IP address), you can try this:

/(?<has address )(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\b/

That should match four numbers from 0-255, delimited by dots and preceded by 'has address '.


Using GNU grep:

host example.org | grep -Po '.*has address \K[0-9.]*'


host exmaple.org | sed -n 's/^.* (.*)$/\1/p'

0

精彩评论

暂无评论...
验证码 换一张
取 消