[笔记] grep用法:数量统计和搜索html中的url
★ 1. 数量统计
实例:可以用来统计CVE列表中包含android的问题有多少,包含linux的问题有多少。
例如,CVE问题列表:http://cve.mitre.org/data/downloads/allitems.csv
这是csv格式的,每个问题占一行。
为简要说明grep的用法,只举简单明了的例子,例如,统计包含字符串android
的行数。
注:测试环境为cygwin。
♦ 1.1 构造测试数据
$ echo -e "android, android\nandroid,android\nandroid\nandroid,linux\nlinux,linux\nlinux" > test.txt
注:echo的参数-e
表示解析转义字符,例如上面字符串里的\n
,会被认为是换行符。
test.txt的内容为:
$ cat test.txt
android, android
android,android
android
android,linux
linux,linux
linux
♦ 1.2 统计包含android
、linux
的行数
利用grep的-c
参数,-c
用来只显示匹配的行数。
- 出现
android
的行数:
$ grep -ic "android" ./test.txt
4
$ grep -ni "android" ./test.txt
1:android, android
2:android,android
3:android
4:android,linux
- 同样,出现
linux
的行数:
$ grep -ic "linux" ./test.txt
3
$ grep -ni "linux" ./test.txt
4:android,linux
5:linux,linux
6:linux
- 统计包含
android
或包含linux
的行数:
$ grep -ic "android\|linux" ./test.txt
6
那么,同时包含android
和linux
的行数是:
4+3−6=1
★ 2. 搜索html中的url
♦ 2.1 找个例子文件
以http://slide.ent.sina.com.cn/star/slide_4_704_254805.html#p=10
为例。
Firefox浏览器,通过“开发者”-> “查看器”(或者使用快捷ctrl+shift+c),找到html文件,并保存下来。
♦ 2.2 搜索html中所有的http开头的url
使用grep -wio "http://[0-9_a-zA-Z\/.\-]*" ./test.html
- 参数
-w
:整个pattern匹配,例如要完整匹配http://[0-9_a-zA-Z\/.\-]*
- 参数
-i
:忽略大小写 - 参数
-o
:表示只显示匹配的部分。
对于这个正则表达式,可以不用-i
参数的。因为字符集[0-9_a-zA-Z\/.\-]
包含了大小写。
需要注意的是:-
必须在最后。否则有可能匹配不上。在python中,-
在中间位置是没有问题。
运行结果(部分结果):
$ grep -wio "http://[0-9_a-zA-Z\/.\-]*" ./test.html
http://ent.sina.com.cn/js/470/20130123/comment.js
http://comment5.news.sina.com.cn/count/info
http://beacon.sina.com.cn/ckctl.html
http://i.sso.sina.com.cn/images/login/icon_custom.png
http://api.sina.com.cn/weibo/2/users/show.json
http://n.sinaimg.cn/ent/4_img/upload/d411fbc6/w1280h960/20171201/TBHA-fypikwt0416669.jpg
略
♦ 2.3 搜索html中所有的http开头的图片
grep -wio "http://[0-9_a-zA-Z\/.\-]*\(.jpg|.png\)" ./test.html
这里的\(.jpg|.png\)
表示.jpg
和.png
都是要搜索的。
$ grep -wio "http://[0-9_a-zA-Z\/.\-]*\(.jpg\|.png\)" ./test.html
http://www.sinaimg.cn/dy/deco/2013/0604/dot_hover.png
http://www.sinaimg.cn/dy/deco/2013/0604/weibo.png
http://www.sinaimg.cn/dy/deco/2013/0604/weibo_hover.png
http://www.sinaimg.cn/cj/hd/close_h2.jpg
http://n.sinaimg.cn/ent/4_img/upload/d411fbc6/w800h600/20171201/ZZ5M-fypikwt0416547.jpg
http://www.sinaimg.cn/ent/deco/2014/0311/images/sc_pic_loginImage.png
http://n.sinaimg.cn/ent/4_img/upload/d411fbc6/w1280h960/20171201/TBHA-fypikwt0416669.jpg
略
♦ 2.4 只搜索"http://n.sinaimg.cn
开头的jpg图片
grep -wio "http://n.sinaimg.cn[0-9_a-zA-Z\/.\-]*.jpg" ./test.html
由于原始html中有重复的url,所以匹配出来的也是有重复的。
$ grep -wio "http://n.sinaimg.cn[0-9_a-zA-Z\/.\-]*.jpg" ./test.html
http://n.sinaimg.cn/ent/4_img/upload/d411fbc6/w800h600/20171201/ZZ5M-fypikwt0416547.jpg
http://n.sinaimg.cn/ent/4_img/upload/d411fbc6/w1280h960/20171201/TBHA-fypikwt0416669.jpg
http://n.sinaimg.cn/ent/4_img/upload/d411fbc6/w800h600/20171201/ZZ5M-fypikwt0416547.jpg
http://n.sinaimg.cn/ent/4_img/upload/d411fbc6/w800h600/20171201/EtX1-fypikwt0416552.jpg
略