2

我编写了一个脚本,它读取网页的 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 脚本的新手?

4

2 回答 2

7
$ 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
于 2012-07-25T07:12:52.023 回答
6

像这样

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
于 2012-07-25T07:11:26.463 回答