使用regex和sed过滤掉IP

时间:2011-02-24 16:33:49

标签: regex linux command-line sed

我在将正则表达式转换为Centos 5.5上的工作sed命令时遇到了麻烦。

我想从字符串中过滤掉IP地址:

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

到目前为止我的正则表达式是:

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

使用sed的命令示例是:

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

但我从那个命令回来的是sed的输入:“example.org的地址是123.45.67.890”

有什么想法吗?

6 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:2)

如果没有正则表达式,这是一种非常简单的方法:

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

答案 2 :(得分:1)

你真的不需要sed。您可以使用cut来解析空格:

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

这只取第四个单词,用空格分隔。

答案 3 :(得分:0)

您的([a-zA-Z\. ]+)会捕获IP地址前的所有内容,并将其包含在匹配项中。如果域名中包含任何数字,它也会导致匹配失败。使用lookbehind:

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

你显然是need to use Perl mode for sed to support lookbehinds。您也可以使用捕获组。如果你想要一个更具辨别力的模式(即只匹配看起来非常像IP地址的东西),你可以试试这个:

/(?<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/

这应该匹配0-255中的四个数字,由点分隔,前面是'有地址'。

答案 4 :(得分:0)

使用GNU grep

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

答案 5 :(得分:0)

主持人exmaple.org | sed -n's /^.*(。*)$ / \ 1 / p'