1

What I want to do is something like below. I have a URL, say http://www.google.com/one/two/three

I need to extract the main domain name "www.google.com", to feed it to nslookup (As nslookup/dig does not seem to work with full URL) and then replace the URL with resolved IP address.e.g.

$ echo "http://www.google.com/one/two/three" | sed "s/<pattern>//g" 
$ www.google.com

The problem is that "http://" may not always be there. And then

$ echo "http://www.google.com/one/two/three" | sed "s/<pattern>//g" 
$ http://11.22.33.44/one/two/three

Can anyone provide any related link or related examples ?

4

2 回答 2

5

试试这个 sed 命令:

echo "http://www.google.com/one/two/three" | sed -r 's#(https?://)?([^/]+).*#\2#'

输出:

www.google.com

当您获取 IP 地址时:

$> IP="11.22.33.44"
$> echo "https://www.google.com/one/two/three" | sed -r "s#(https?://)?([^/]+)(.*)#\1$IP\3#"
https://11.22.33.44/one/two/three

这将在 URL 之前http://使用https://或不使用任何内容。https?://

于 2013-08-06T18:09:08.013 回答
1

由于在一般情况下 URL 可能很混乱(“ http://user:pass@www.example.com:8080/one/two/three ”),我建议使用带有 URI 解析库的语言。例如

url="http://stackoverflow.com/questions/18087200/replace-part-of-url-with-ip-adress"
newurl=$(perl -MURI -le '
    $uri = URI->new(shift);
    $cmd = "nslookup " . $uri->host;
    $out = qx($cmd);
    if ($out =~ /Name:.*?\KAddress:\s+([\d.]+)/s) { 
        $ip = $1;
        $uri->host($ip);
        print $uri
    } else {warn "cannot find IP address in nslookup output"}
' "$url")
echo "$newurl"

输出

http://198.252.206.16/questions/18087200/replace-part-of-url-with-ip-adress
于 2013-08-06T19:18:43.593 回答