centos7.4 grep常用用法

grep是Linux中最常用的"文本处理工具"之一,grep与sed、awk合称为Linux中的三剑客。

grep的全称为: Global search Regular Expression and Print out the line

全称中的"Global search"为全局搜索之意。

全称中的"Regular Expression"表示正则表达式。

所以,从grep的全称中可以了解到,grep是一个可以利用"正则表达式"进行"全局搜索"的工具,grep会在文本文件中按照指定的正则进行全局搜索,并将搜索出的行打印出来。

当然,不使用正则表达式时也可以使用grep,但是当grep与正则表达式结合在一起时,威力更强大。

实例文件:

Now stand you on the top of happy hours,

  And many maiden gardens, yet unset,

  With virtuous wish would bear your living flowers,

  Much liker than your painted counterfeit:

  So should the lines of life that life repair

  Which this time's pencil or my pupil pen,

  Neither in inward worth nor outward fair

  Can make you live yourself in eyes of me.

  To give away yourself keeps yourself still,

  And you must live, drawn by your own sweet skill.

  1.最简单字符串查询 

查询包含you的句子:

 

 要显示所属的行,使用-n选选项

 

 查询完整的单词,使用-w选项

 

 忽略大小写使用-i选项

 

 通过使用-c选项,计算单词出现的个数:

 

 2.正则表达式的使用

 

正则表达式使用-E选项
 
查询包含and或者you

 

 查询包含an以及后边的任意字符

 

 3.反向选择

排除选择的字符使用-v选项

查询没有and的行,并显示行号

 

 4.查询选择行的前后行

查询选中行的后一行,使用-A[num] num可以是一个数字

 

 查询选中行的前一行,使用-B[num] num是一个数字

 

查询选中行的上下几行,使用-C[num] num是一个数字,表示要选中的行数

 

 

 

posted @ 2019-10-23 17:27  whyld  阅读(3413)  评论(0编辑  收藏  举报