grep命令是文本搜索命令,它可以正则表达式搜索文本,也可从一个文件中的内容作为搜索关键字,本篇文章重点为大家讲解一下grep命令使用实例。

示例实战
废话不说了,直接实战。文章中的示例 需要一个样例文件,文件内容如下:

\1. 把包含 syslog 的行过滤出来

\2. 把以 ntp 开头的行过滤出来

\3. 把匹配 ntp 的行以及下边的两行过滤出来
\4. 把包含 syslog 及上边的一行过滤出来

\5. 把包含 syslog 以及上、下一行内容过滤出来

\6. 过滤某个关键词,并输出行号

\7. 过滤不包含某关键词,并输出行号

\8. 删除掉空行

\9. 过滤包含 root 或 syslog 的行

\9. 过滤包含 root 或 syslog 的行

简单总结
通过了一些简单案例操作,我们应该已经熟悉了 grep 的常见用法,下边再来简单总结 grep 的常见选项,相信在实战练习后再来总结应该会有更好的学习效果。
-A:除了匹配行,额外显示该行之后的N行 -B:除了匹配行,额外显示该行之前的N行 -C:除了匹配行,额外显示该行前后的N行 -c:统计匹配的行数 -e:实现多个选项间的逻辑 or 关系 -E:支持扩展的正则表达式 -F:相当于 fgrep -i:忽略大小写 -n:显示匹配的行号 -o:仅显示匹配到的字符串 -q:安静模式,不输出任何信息,脚本中常用 -s:不显示错误信息 -v:显示不被匹配到的行 -w:显示整个单词 –color:以颜色突出显示匹配到的字符串
与 grep 相似的工具还有 egrep、fgrep,实用性并不强,其功能完全可以通过 grep 的扩展参数来实现,所以就不再扩展。
以上就是良许教程网为各位朋友分享的Linux系统相关内容。想要了解更多Linux相关知识记得关注公众号“良许Linux”,或扫描下方二维码进行关注,更多干货等着你 !
