【问题标题】:How to extract domain name from url?如何从url中提取域名?
【发布时间】:2022-04-02 12:26:28
【问题描述】:

如何使用 bash 从 url 中提取域名? 喜欢:http://example.com/ 到 example.com 必须适用于任何顶级域名,而不仅仅是 .com

【问题讨论】:

标签: regex bash url


【解决方案1】:

您可以使用简单的AWK方式提取域名如下:

echo http://example.com/index.php | awk -F[/:] '{print $4}'

输出:example.com

:-)

【讨论】:

  • 很好,这比stackoverflow.com/questions/6174220/parse-url-in-shell-script 中提供的答案好多了!
  • echo http://example.com:3030/index.php | awk -F/ '{print $3}' example.com:3030 :-(
  • 您可以再次拆分 : 以获取它,但它不够灵活,无法同时接受有端口和无端口。
  • 我用这个得到了它 - echo http://www.example.com/somedir/someotherdir/index.html | cut -d'/' -f1,2,3 给出http://www.example.com
  • 处理带有和不带有端口的 url:awk -F[/:] '{print $4}'
【解决方案2】:
$ URI="http://user:pw@example.com:80/"
$ echo $URI | sed -e 's/[^/]*\/\/\([^@]*@\)\?\([^:/]*\).*/\2/'
example.com

http://en.wikipedia.org/wiki/URI_scheme

【讨论】:

  • 这适用于有或没有端口、深度路径并且仍在使用 bash。虽然它在 mac 上不起作用。
  • 7 年后,这仍然是我的首选答案。
  • 我使用你的建议加上一些额外的内容来删除可能在 url 中的任何子域 ->> echo http://www.mail.example.com:3030/index.php | sed -e "s/[^/]*\/\/\([^@]*@\)\?\([^:/]*\).*/\2/" | awk -F. '{print $(NF-1) "." $NF}' 所以我基本上在点处截断你的输出并取最后一个和倒数第二个列并用点修补它们。
  • 这是最好的答案!我将它用于允许完整 URL 的 ping 命令:unix.stackexchange.com/a/428990/20661 仅剥离 www. 子域
  • 想拿到端口的人:sed -e "s/[^/]*\/\/\([^@]*@\)\?\([^:/]*\)\(:\([0-9]\{1,5\}\)\)\?.*/\4/"
【解决方案3】:
basename "http://example.com"

当然,这不适用于这样的 URI:http://www.example.com/index.html,但您可以执行以下操作:

basename $(dirname "http://www.example.com/index.html")

或者对于更复杂的 URI:

echo "http://www.example.com/somedir/someotherdir/index.html" | cut -d'/' -f3

-d 表示“分隔符”,-f 表示“字段”;在上面的示例中,由正斜杠“/”分隔的第三个字段是 www.example.com。

【讨论】:

  • 我喜欢 cut -d'/' -f3 的简单性。
  • 添加端口失败:echo "http://www.example.com:8080/somedir/someotherdir/index.html" | cut -d'/' -f3
  • 得到这个 - http://www.example.com 通过运行 - echo http://www.example.com/somedir/someotherdir/index.html | cut -d'/' -f1,2,3
  • basename $(dirname 不起作用,如果 url 以域结尾,例如:basename $(dirname "http://www.example.com/") 将仅显示:http:
【解决方案4】:
echo $URL | cut -d'/' -f3 | cut -d':' -f1

适用于 URL:

http://host.example.com
http://host.example.com/hi/there
http://host.example.com:2345/hi/there
http://host.example.com:2345

【讨论】:

  • 我发现这更有用,因为它会返回不包含“http://”的 url,即abc.com 将保留为abc.com
  • 这其实是这里所有答案中最直观、最简洁、最有效的方法了!
  • 这会提取 host.example.com 而不是请求的域名 (example.com)。
【解决方案5】:
sed -E -e 's_.*://([^/@]*@)?([^/:]+).*_\2_'

例如

$ sed -E -e 's_.*://([^/@]*@)?([^/:]+).*_\2_' <<< 'http://example.com'
example.com

$ sed -E -e 's_.*://([^/@]*@)?([^/:]+).*_\2_' <<< 'https://example.com'
example.com

$ sed -E -e 's_.*://([^/@]*@)?([^/:]+).*_\2_' <<< 'http://example.com:1234/some/path'
example.com

$ sed -E -e 's_.*://([^/@]*@)?([^/:]+).*_\2_' <<< 'http://user:pass@example.com:1234/some/path'
example.com

$ sed -E -e 's_.*://([^/@]*@)?([^/:]+).*_\2_' <<< 'http://user:pass@example.com:1234/some/path#fragment'
example.com

$ sed -E -e 's_.*://([^/@]*@)?([^/:]+).*_\2_' <<< 'http://user:pass@example.com:1234/some/path#fragment?params=true'
example.com

【讨论】:

  • 轰隆隆! HOST=$(sed -E -e 's_.*://([^/@]*@)?([^/:]+).*_\2_' &lt;&lt;&lt; "$MYURL") 在 Bash 中很好
  • 我想从域中裁剪 www。在这种情况下,我应该如何正确更改命令?
  • 感谢这个,非常方便,从 URL 捕获路径我稍微扩展了这个 sed -E -e 's_.*://([^/@]*@)?([^/:]+)(.*)_\2_' &lt;&lt;&lt; 'http://example.com' 这允许您从 url 获取路径 sed -E -e 's_.*://([^ /@]*@)?([^/:]+)(.*)_\3_' example.com/path/to/something'
【解决方案6】:
#!/usr/bin/perl -w
use strict;

my $url = $ARGV[0];

if($url =~ /([^:]*:\/\/)?([^\/]+\.[^\/]+)/g) {
  print $2;
}

用法:

./test.pl 'https://example.com'
example.com

./test.pl 'https://www.example.com/'
www.example.com

./test.pl 'example.org/'
example.org

 ./test.pl 'example.org'
example.org

./test.pl 'example'  -> no output

如果您只想要域而不是完整的主机 + 域,请改用:

#!/usr/bin/perl -w
use strict;

my $url = $ARGV[0];
if($url =~ /([^:]*:\/\/)?([^\/]*\.)*([^\/\.]+\.[^\/]+)/g) {
  print $3;
}

【讨论】:

【解决方案7】:

您可以使用 python 的 urlparse,而不是使用正则表达式来执行此操作:

 URL=http://www.example.com

 python -c "from urlparse import urlparse
 url = urlparse('$URL')
 print url.netloc"

您可以像这样使用它,也可以将它放在一个小脚本中。但是,这仍然需要一个有效的方案标识符,查看您的评论,您的输入不一定提供一个。您可以指定默认方案,但 urlparse 期望 netloc 以 '//' 开头:

url = urlparse('//www.example.com/index.html','http')

所以你必须手动添加这些,即:

 python -c "from urlparse import urlparse
 if '$URL'.find('://') == -1 then:
   url = urlparse('//$URL','http')
 else:
   url = urlparse('$URL')
 print url.netloc"

【讨论】:

    【解决方案8】:

    关于如何获取这些网址的信息很少……请下次显示更多信息。 url中是否有参数等... 同时,只需对您的示例网址进行简单的字符串操作

    例如

    $ s="http://example.com/index.php"
    $ echo ${s/%/*}  #get rid of last "/" onwards
    http://example.com
    $ s=${s/%\//}  
    $ echo ${s/#http:\/\//} # get rid of http://
    example.com
    

    其他方式, 使用 sed(GNU)

    $ echo $s | sed 's/http:\/\///;s|\/.*||'
    example.com
    

    使用 awk

    $ echo $s| awk '{gsub("http://|/.*","")}1'
    example.com
    

    【讨论】:

    • 你的方法不行!回声example.com/index.php | sed -r 's/http:\/\/|\///g' 在 cygwin 上给出输出 example.comindex.php 而不是 example.com。请发布一个有效的方法
    • 我的方法不起作用,因为您的示例网址不同!并且您没有提供有关要解析的网址类型的更多信息!您应该清楚地写出您的问题,提供输入示例并描述您下次想要的输出!
    • 第二行似乎不正确。我将前 2 行复制粘贴到我的 ubuntu shell 并得到 example.com/index.php*
    【解决方案9】:

    下面会输出“example.com”:

    URI="http://user@example.com/foo/bar/baz/?lala=foo" 
    ruby -ruri -e "p URI.parse('$URI').host"
    

    有关如何使用 Ruby 的 URI 类的更多信息,您必须咨询the docs

    【讨论】:

      【解决方案10】:

      这是 node.js 的方式,它可以使用或不使用端口和深度路径:

      //get-hostname.js
      'use strict';
      
      const url = require('url');
      const parts = url.parse(process.argv[2]);
      
      console.log(parts.hostname);
      

      可以这样称呼:

      node get-hostname.js http://foo.example.com:8080/test/1/2/3.html
      //foo.example.com
      

      文档:https://nodejs.org/api/url.html

      【讨论】:

        【解决方案11】:

        一种涵盖更多情况的解决方案将基于 sed 正则表达式:

        echo http://example.com/index.php | sed -e 's#^https://\|^http://##' -e 's#:.*##' -e 's#/.*##'

        这适用于以下网址: http://example.com/index.php, http://example.com:4040/index.php, https://example.com/index.php

        【讨论】:

          【解决方案12】:

          借助 Ruby,您可以使用 Domainatrix 库/gem

          http://www.pauldix.net/2009/12/parse-domains-from-urls-easily-with-domainatrix.html

          需要“红宝石” 需要“域矩阵” s = 'http://www.champa.kku.ac.th/dir1/dir2/file?option1&option2' url = Domainatrix.parse(s) url.domain => “kku”

          很棒的工具! :-)

          【讨论】:

            【解决方案13】:

            没有任何子外壳或子进程的纯 Bash 实现:

            # Extract host from an URL
            #   $1: URL
            function extractHost {
                local s="$1"
                s="${s/#*:\/\/}" # Parameter Expansion & Pattern Matching
                echo -n "${s/%+(:*|\/*)}"
            }
            

            例如extractHost "docker://1.2.3.4:1234/a/v/c" 将输出1.2.3.4

            【讨论】:

              猜你喜欢
              • 2021-04-12
              • 2010-11-07
              • 2010-10-24
              • 2013-09-17
              • 2011-05-06
              • 2017-10-16
              • 2018-09-08
              • 1970-01-01
              • 2010-10-08
              相关资源
              最近更新 更多