1 多个关键字查找
1.1 使用-e
- grep -e 'stdio\.h' -e 'stdlib\.h' /usr/include/*.h
1.2 使用-f file
将关键字以行方式保存在一个文件中
1.3 使用元字符 \|
- grep 'stdio\.h\|stdlib.h' /usr/include/*.h
1.4 多关键字 and 查找
- grep 'stdio\.h\|stdlib.h' /usr/include/*.h
2. 单词匹配
-w(gnu 选项)
- grep -w 'main' /usr/include/*.h
\<\>
- grep '\<main\>' /usr/include/*.h
2.善用 -E
-E选项启用 extended expression,正则写起来更加灵活
例如匹配一行内两个连续重复the或that或and或or
- man gcc | grep -E '(\<the\>|\<that\>|\<and\>|\<or\>) \1'
3 多文件查找
- grep -l 'main' *.c
4 忽略大小写 -i
- grep -i -w 'sTAt' /usr/include/*.h
5 递归查找 -r(posix 未说明)
- grep -i -w -r -E 'error|failed|failure' /var/log |less
6 显示匹配行周围行 (posix 未说明)
B/A/C(before/after/context
-B n
-A n
-C n
- grep -w -i -C 3 'struct stat' /usr/include/*.h
7 取反-v
- grep -v -w 'hello' filename
如果没有取反,世界将不再美丽
8 匹配数 -c
- echo aaaa | grep -c 'a'
这个输出是1!因为grep是行匹配的
9 输出文件名 -l
- grep -l -r -i -w 'filename_max' /usr/include/*.h
10 只输出匹配部分-o (gnu 选项)
- echo abcddf |grep -o 'dd'
可以用于验证自己写的正则