grep是在终端下,从文件中筛选文本最常用的工具.估计大多数人停留在cat file|grep xxx或者grep xxx file的阶段.其实这是个超级强大的工具,今天就进行简单的初探.
操作对象:『The Zen Of Python』
$ python -c 'import this' |tee a.txt
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
其它基本用法
-c count出现次数
-n number显示行
-v 排除
-i 忽略大小写
友情提示,以下演示在有颜色的终端下,效果更佳
匹配后输出前后行
后面(After)一行 -A 1
$ grep 'Unless explicitly' -nA 1 a.txt
13:Unless explicitly silenced.
14-In the face of ambiguity, refuse the temptation to guess.
前面(Before)一行 -B 1
grep 'Unless explicitly' -nB 1 a.txt
12-Errors should never pass silently.
13:Unless explicitly silenced.
前后各一行 -1 或 -C 1
$ grep 'Unless explicitly' -n1 a.txt
12-Errors should never pass silently.
13:Unless explicitly silenced.
14-In the face of ambiguity, refuse the temptation to guess.
$ grep 'Unless explicitly' -nC 1 a.txt
12-Errors should never pass silently.
13:Unless explicitly silenced.
14-In the face of ambiguity, refuse the temptation to guess.
匹配后输出前后几个字符
查找的字符串为Python
前三个字符
$ grep -o -P '.{0,3}Python' a.txt
of Python
后五个字符
$ grep -o -P 'Python.{0,5}' a.txt
Python, by
前三后五个字符
$ grep -o -P '.{0,3}Python.{0,5}' a.txt
of Python, by
文件匹配
排除a.txt里存在的内容
$ grep -vf b.txt a.txt
高亮匹配项
检查nginx是否包含模块
$ nginx -V 2>&1 | grep -o with-http_stub_status_module
with-http_stub_status_module
相关博文