简体   繁体   中英

Filter out IP using regex and sed

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 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 }'

这是一种无需正则表达式的非常简单的方法:

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.

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

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 (ie 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 '.

使用GNU grep

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM