grep

[翻译] grep command in Unix/Linux

grep (gloabally search for regular expression and print out) 过滤器在一个文件中搜索由字符组成的特定的表达式并且展示所有匹配表达式的行。在搜索过程中这个表达式会被处理成正则表达式使用。

语法

grep [options] pattern [files]

参数说明
  • -c: 匹配的行数。
  • -h: 展示匹配行,但是不展示所属文件名
  • -i: 忽略大小写
  • -l: 只展示文件名
  • -n: 展示匹配行和它的行号
  • -v: 反转查找
  • -e <exp>: <正则> 搜索表达式,可以使用多次
  • -f <file>: 使用指定文件的内容搜索,每次一行
  • -E: 将表达式当做扩展正则来使用
  • -w: 匹配单词
  • -o: 只输出文件中匹配到的部分
  • -A after -A5匹配显示的内容,接下来的5行
    cat package.json | grep -A5 scripts
  • -B before -B5 匹配显示的内容,接上来的行
  • -C context -C5 匹配显示的内容,接上下来的行

参考链接

grep command in Unix/Linux

示例

创建示例文件 a.txt,内容:

unix is great os. unix is opensource. unix is free os.
learn operating system.
Unix linux which one you choose.
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.
  1. 忽略大小写

grep -i "UNix" a.txt

结果:

unix is great os. unix is opensource. unix is free os.
Unix linux which one you choose.
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.
  1. 显示匹配行的数量

grep -c "unix" a.txt

结果:

2
  1. 显示匹配的文件

grep -l "unix" * 或 grep -l "unix" f1.txt f2.txt

结果:

a.txt

  1. 查找单词匹配的

grep -w "unix" a.txt
结果:

unix is great os. unix is opensource. unix is free os.
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

  1. 只展示匹配的部分

grep -o "unix" a.txt
结果:

unix
unix
unix
unix
unix
unix

  1. 显示行号

grep -n "unix" a.txt

结果:

1:unix is great os. unix is opensource. unix is free os.
4:uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

  1. 反转搜索

grep -v "unix" a.txt

结果:

learn operating system.
Unix linux which one you choose.

  1. 匹配行首是以某个字符串开头的行 (正则表达式的运用)

grep "^unix" a.txt

结果:

unix is great os. unix is opensource. unix is free os.

  1. 使用-e 参数,能匹配多个

grep -e "unix" -e "Unix" -e "UNix" a.txt

结果:

unix is great os. unix is opensource. unix is free os.
Unix linux which one you choose.
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

  1. 匹配特定文件里面的表达式
    创建文件 pattern.txt,内容(其实和上例是一样的):
unix
Unix
UNix

grep -f pattern.txt a.txt

结果:

unix is great os. unix is opensource. unix is free os.
Unix linux which one you choose.
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 项目上线之后,或者在测试环境,经常会有bug让我们去排查和修改,这个时候,我们需要在linux系统中使用一些命令帮...
    时之令阅读 2,864评论 0 2
  • http://blog.sina.com.cn/s/blog_47d5f1b801015ea7.html首先要记住...
    水平阅读 1,196评论 0 2
  • 如果你是一个新手,请从头阅读这篇文章,如果你只是忘记了grep命令的一些常用选项,直接查看文章尾部的总结部分即可。...
    082e63dc752b阅读 1,057评论 0 0
  • Linux系统中grep命令是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来。grep全...
    宝贝小魔阅读 405评论 0 1
  • 1.作用 Linux系统中grep命令是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹 配的行打印出来...
    流川枫丶阅读 1,431评论 0 9