0 Comments

grep 命令基本用法(1)

发布于:2012-12-15  |   作者:广州网站建设  |   已聚集:人围观

grep命令是支持正则表达式的一个多用途文本搜索工具,grep的一般格式为:


  1. grep [选项][模式][文件…] 广州网站建设

grep命令由选项、模式和文件三部分组成,它在一个或多个文件中搜索满足模式的文本行,模板后的所有字符串被看做文件名,文件名可以有多个,搜索的结果被打印到屏幕,不影响原文件的内容。grep命令的选项用于对搜索过程进行补充说明,grep命令的选项及其意义如表3-3 所示。

表3-3 grep命令选项及其意义

        grep命令的模式十分灵活,可以是字符串,也可以是变量,还可以是正则表达式。需要说明的是,无论模式是何种形式,只要模式中包含空格,就需要使用双引号将模式引起来,如果不加双引号,空格后的单词容易被误认为是文件名,如普通字符串为"hello world",grephello world命令就将world认为是文件名,因此,grep"hello world"filename才是正确的写法。大部分情况下,使用单引号将模式引起来也是可以的,第6 章将详细讨论双引号和单引号的区别,在此,我们只简单告诉读者:一旦模式中包含空格,就需要使用双引号或单引号将模式引起来。下面的例3-24 可以充分验证这个观点。

  1. #例3-24:模式包含空格时,是否使用双引号的区别  
  2. #搜索00.pem 文件中包含certificate字符串的行,不需要引号引起模式  
  3. [root@zawu globus]# grep certificate 00.pem  
  4. The above string is known as your user certificate subject, and it  
  5. To install this user certificate, please save this e-mail message  
  6. If you have any questions about the certificate contact  
  7. #若需要搜索00.pem 文件中包含user certificate字符串的行  
  8. #我们看一看不用引号将user certificate引起来的结果  
  9. [root@zawu globus]# grep user certificate 00.pem  
  10. grep: certificate: 没有那个文件或目录  
  11. #Shell将certificate 解析为文件名,提示没有此文件的错误  
  12. #下面给出00.pem文件中包含user 字符串的行  
  13. 00.pem:The above string is known as your user certificate subject, and it  
  14. 00.pem:uniquely identifies this user.  
  15. 00.pem:To install this user certificate, please save this e-mail message  
  16. 00.pem:/home/globus/.globus/usercert.pem  
  17. #用引号将user certificate引起来后得到正确的结果  
  18. [root@zawu globus]# grep "user certificate" 00.pem  
  19. The above string is known as your user certificate subject, and it  
  20. To install this user certificate, please save this e-mail message  
  21. [root@zawu globus]# 

       例3-24 首先搜索00.pem文件中包含certificate 字符串的行,由于模式certificate 中不包含空格,因此,是否用引号引起模式对grep 命令不产生影响。当我们要搜索00.pem 文件中包含user certificate 字符串的行时,不用双引号将user certificate 括起来时,Shell 提示没有certificate 这个文件或目录,然后,给出00.pem 文件中包含user 字符串的行,这说明Shell将grep user certificate 00.pem这条命令解释为在certificate和00.pem两个文件中搜索包含user字符串的行,这显然与我们的初衷不符。而当我们用双引号将user certificate括起来后,就得到了正确的结果。

grep支持多文件查询,请看下面的例3-25。


  1. #例3-25:演示grep 的多文件查询  
  2. [root@zawu globus]# grep Certificate 00.pem 08.pem  
  3. 00.pem:This is a Certificate Request file:  
  4. 00.pem:Certificate Subject:  
  5. 08.pem:Certificate:  
  6. [root@zawu globus]# 

上例搜索00.pem 和08.pem 两个文件中包含Certificate 字符串的行,命令逐个给出待搜索的文件,结果打印出所有包含Certificate字符串的行,并以文件名开头。

飞机