【问题标题】:Looping through a text file containing domains using bash script使用 bash 脚本遍历包含域的文本文件
【发布时间】:2012-07-25 07:07:47
【问题描述】:

我编写了一个脚本,它读取网页的 href 标记并获取该网页上的链接并将它们写入文本文件。现在我有一个包含这些链接的文本文件,例如:

http://news.bbc.co.uk/2/hi/health/default.stm
http://news.bbc.co.uk/weather/
http://news.bbc.co.uk/weather/forecast/8?area=London
http://newsvote.bbc.co.uk/1/shared/fds/hi/business/market_data/overview/default.stm
http://purl.org/dc/terms/
http://static.bbci.co.uk/bbcdotcom/0.3.131/style/3pt_ads.css
http://static.bbci.co.uk/frameworks/barlesque/2.8.7/desktop/3.5/style/main.css
http://static.bbci.co.uk/frameworks/pulsesurvey/0.7.0/style/pulse.css
http://static.bbci.co.uk/wwhomepage-3.5/1.0.48/css/bundles/ie6.css
http://static.bbci.co.uk/wwhomepage-3.5/1.0.48/css/bundles/ie7.css
http://static.bbci.co.uk/wwhomepage-3.5/1.0.48/css/bundles/ie8.css
http://static.bbci.co.uk/wwhomepage-3.5/1.0.48/css/bundles/main.css
http://static.bbci.co.uk/wwhomepage-3.5/1.0.48/img/iphone.png
http://www.bbcamerica.com/
http://www.bbc.com/future
http://www.bbc.com/future/
http://www.bbc.com/future/story/20120719-how-to-land-on-mars
http://www.bbc.com/future/story/20120719-road-opens-for-connected-cars
http://www.bbc.com/future/story/20120724-in-search-of-aliens
http://www.bbc.com/news/

我希望能够过滤它们,以便我返回如下内容:

http://www.bbc.com : 6
http://static.bbci.co.uk: 15

旁边的值表示域在文件中出现的次数。考虑到我将有一个循环遍历文件,我如何能够在 bash 中实现这一点。我是 bash shell 脚本的新手?

【问题讨论】:

    标签: linux bash loops


    【解决方案1】:
    $ cut -d/ -f-3 urls.txt | sort | uniq -c                  
    3 http://news.bbc.co.uk
    1 http://newsvote.bbc.co.uk
    1 http://purl.org
    8 http://static.bbci.co.uk
    1 http://www.bbcamerica.com
    6 http://www.bbc.com
    

    【讨论】:

    • 输出格式错误。这是修复它的sed| sed -e 's/ *\([0-9]*\) \(.*\)/\2: \1/'
    • 实际上,OP 说“返回 类似”,所以答案很好:) 但评论和您的解决方案很有用。
    【解决方案2】:

    就这样

    egrep -o '^http://[^/]+' domain.txt | sort | uniq -c
    

    在您的示例数据上输出:

    3 http://news.bbc.co.uk/
    1 http://newsvote.bbc.co.uk/
    1 http://purl.org/
    8 http://static.bbci.co.uk/
    6 http://www.bbc.com/
    1 http://www.bbcamerica.com/
    

    即使您的行由一个没有尾部斜杠的简单 url 组成,此解决方案也有效,所以

    http://www.bbc.com/news
    http://www.bbc.com/
    http://www.bbc.com
    

    都将在同一个组中。

    如果你想允许https,那么你可以写:

    egrep -o '^https?://[^/]+' domain.txt | sort | uniq -c
    

    如果其他协议是可能的,比如ftp、mailto等,你甚至可以很松散地写:

    egrep -o '^[^:]+://[^/]+' domain.txt | sort | uniq -c
    

    【讨论】:

    • +1 嘿,好球!我将 OP 的代码粘贴到一个文本编辑器窗口中,该窗口以 Wikipedia url 作为唯一行。第一个 bbc.co.uk 行从该行的末尾开始,所以我最终只得到了 2 个 bbc.co.uk。清理干净了。
    • 我喜欢使用-o,这对我来说是新的。
    • 如果有一个没有斜杠的基本域会发生什么,例如http://exmaple.com?它将被排除在外。
    • @Sorpigal 我已经编辑了答案以适应该问题,并添加了一些其他可能有用的注释。
    猜你喜欢
    • 1970-01-01
    • 2021-05-31
    • 2018-10-03
    • 1970-01-01
    • 2022-01-21
    • 2023-03-15
    • 2020-05-16
    • 2020-01-16
    • 1970-01-01
    相关资源
    最近更新 更多