grep和egrep都是过滤器,egrep是扩展的意思,支持扩展正则表达式
语法格式
grep [option] [pattern] [file1, file2, ...]
command | grep [option] [pattern]
参数:掌握
- -v 不显示匹配行信息
- -i 搜索时忽略大小写
- -n 显示行号
- -r 递归搜索
- -E 支持扩展正则表达式
- -F 不按正则表达式匹配,按照字符串字面意思匹配
参数:了解
- -c 只输出匹配行的数量,不显示具体内容
- -w 匹配整词
- -x 匹配整行
- -l 只列出匹配的文件名,不显示具体匹配行内容
举例
多个参数
grep -ni python file
file文件
i love python
lovelove python
loooove
I LOVE PYTHON
I Love pYtHoN
I like py.*
正则表达式相关
直接按字符串查找
grep "py" file
i love python
lovelove python
I like py.*
基本的正则表达式
grep "py.*" file
i love python
lovelove python
I like py.*
扩展的正则表达式:grep不支持扩展的正则表达式
grep "python|PYTHON" file
输出为空
扩展的正则表达式:grep+参数-E
grep -E "python|PYTHON" file
i love python
lovelove python
I LOVE PYTHON
不使用正则表达式,只按字面意思匹配
grep -F "py.*" file
I like py.*
递归搜索:递归搜索当前目录下的所有文件
grep -r love ./
.//file:i love python
.//file:lovelove python
.//test1/test1:i love java
.//hello.txt:i love python
grep love file
i love python
lovelove python
匹配整词,即次的前后必须有空白字符(空格键、Tab键、换行符),这边可以看到lovelove python行也包括love子串,但是不是作为一个单词出现的,没有空白字符隔开,故不显示
grep -w love file
i love python
匹配整行
grep -x 'i love python' file
i love python
我们可以看到,有i love python行,但是i love pytho不是整行,故匹配不出来
grep -x 'i love pytho' file
没有输出
-l通常和-r配合使用
grep -rl love ./
.//file
.//test1/test1
.//hello.txt