5.2 使用grep搜索文本

grep是Linux下非常强大的基于行的文本搜索工具,使用该工具时,如果匹配到相关信息就会打印出符合条件的所有行。下面列出了该命令常用的参数:


  1. [root@localhost ~]# grep [-ivnc] '

  2. 需要匹配的字符'

  3. 文件名

  4. #-i

  5. 不区分大小写

  6. #-c

  7. 统计包含匹配的行数

  8. #-n

  9. 输出行号

  10. #-v

  11. 反向匹配


为演示grep的用法,这里首先创建一个文件,文件名和文件内容如下:


  1. [root@localhost ~]# cat tomAndJerry.txt The cat's name is Tom, what's the mouse's name?

  2. The mouse's NAME is Jerry

  3. They are good friends


下面要找出含有name的行:


  1. [root@localhost ~]# grep 'name' tomAndJerry.txt The cat's name is Tom, what's the mouse's name?

  2. #

  3. 打印出含有name

  4. 的行的行编号

  5. [root@localhost ~]# grep -n 'name' tomAndJerry.txt 1:The cat's name is Tom, what's the mouse's name?


由于grep区分大小写,所以虽然第二行中含有大写的NAME,但是也不会匹配到。如果希望忽略大小写,可以加上-i参数。


  1. [root@localhost ~]# grep -i 'name' tomAndJerry.txt The cat's name is Tom, what's the mouse's name?

  2. The mouse's Name is Jerry


如果想知道文件中一共有多少包含name的行,可以使用下面的命令。注意到第二条命令和第一条命令只有一个参数的差别,但是输出的结果却是不一样的。了解了-i参数的作用就不难理解了,请读者自行区分以下两条命令的区别。


  1. [root@localhost ~]# grep -c 'name' tomAndJerry.txt 1

  2. [root@localhost ~]# grep -ci 'name' tomAndJerry.txt 2


如果想打印出文件中不包含name的行,可以使用grep的反选参数-v。读者可自行区分以下命令的区别:


  1. [root@localhost ~]# grep -v 'name' tomAndJerry.txt The mouse's Name is Jerry

  2. They are good friends

  3. [root@localhost ~]# grep -vi 'name' tomAndJerry.txt They are good friends


以上命令都可以使用cat命令+管道符改写。比如上一个命令可以这样改写:


  1. [root@localhost ~]# cat tomAndJerry.txt | grep -vi 'name'

  2. They are good friends