三剑客之grep

Grep 是 Global Regular Expression Print 的缩写,它搜索指定文件的内容,匹配指定的模式,默认情况下输出匹配内容所在的行。注意,grep 只支持匹配而不能替换匹配到的内容。

grep语法格式

  • 第一种:grep [option] [pattern] [file1,file2,…]
  • 第二种:commond | grep [option] [pattern]

grep参数

选项 含义
-v 不显示匹配行信息
-i 搜索时忽略大小写
-n 显示行号
-r 递归搜索
-E 支持扩展正则表达式
-F 不an正则表达式匹配,按照字符串字面意思匹配
-A n可以输出匹配行后的n行
-C n可以输出匹配行前后的n行
-c 只显示匹配行总数
-w 匹配整词
-x 匹配整行
-l 只显示文件名,不显示内容
-s 不显示错误信息

练习

必须掌握

选项 说明 命令
-v 显示不匹配pattern行 grep python file
grep -v python file
-i 搜索时忽略大小写 grep -i python file
grep -vi python file
-n 显示行号 grep -n python file
-E 支持扩展的正则表达式 grep -E “python|PYTHON” file
-F 不支持正则表达式,按字符串的字面意思进行匹配 grep -F “py.*” file
-r 递归搜索 grep -r love

需要了解的选项

选项 说明 命令
-c 只输出匹配行的数量,不显示具体内容 grep -c python file
-w 匹配整词 grep -w python file
-x 匹配整行 grep -x python file
-l 只列出匹配的文件名,不显示具体匹配行内容

实战练习

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
root@ubuntu:~# curl -s http://www.baidu.com/s?wd=mp3 | less
root@ubuntu:~# curl -s http://www.baidu.com/s?wd=mp3 | grep -o "结果约[0-9,]*"
结果约2,290,000
root@ubuntu:~# curl -s http://www.baidu.com/s?wd=mp3 | grep -o "结果约[0-9,]*" | grep -o "[0-9,]*"
2,240,000
root@ubuntu:~# curl https://testerhome.com | grep -o 'http://[a-zA-Z0-9\.\-]*'
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0http://www.favicon-generator.org
100 52541 0 52541 0 0 94873 0 --:--:-- --:--:-- --:--:-- 95010
http://test-china.org
http://wetest.qq.com
http://www.infoq.com
http://tieba.baidu.com
http://www.itdks.com
http://www.ucloud.cn
http://www.sendcloud.net

grep和egrep

  • grep默认不支持扩展正则表达式,只支持基础正则表达式
  • 使用grep -E可以支持扩展正则表达式
  • 使用egrep可以支持扩展正则表达式。与grep -E等价