grep:文本过滤工具

xiaohai 2021-07-31 21:26:47 2208人围观 标签: Linux 
简介grep命令是常用个一个命令。能够从文本文件或管道数据流中筛选匹配的行及数据,如果使用正则表达式进行一起使用,功能会更加强大。
说明

  grep命令是常用个一个命令。能够从文本文件或管道数据流中筛选匹配的行及数据,如果使用正则表达式进行一起使用,功能会更加强大。

格式

  grep [option] [pattern] [file]

pattern匹配模式可以是文字符号或正则表达式

常用命令
  • -v:显示不匹配的行或者排除某些行,显示不包含匹配文本的所有行
  • -n:显示匹配行及行号
  • -i:不区分大小写,默认是区分大小写
  • -c:只统计匹配的行数,不是匹配的次数
  • -E:使用扩展命令egrep命令
  • —color=auto:为grep过滤的匹配字符串添加颜色
  • -w:只匹配过滤的单词
  • -o:只输出匹配的内容
示例

1、过滤不包含abc的行

[root@localhost ~]# cat test1.txt 
hello world!
abc def
python
php
habc
grep
ABC 
AbC
OOO

[root@localhost ~]# grep -v 'abc' test1.txt 
hello world!
python
php
grep
ABC 
AbC
OOO

2、显示过滤内容的行号

[root@localhost ~]# grep -n 'abc' test1.txt 
2:abc def
5:habc

3、不区分大小写

[root@localhost ~]# grep -i 'abc' test1.txt 
abc def
habc
ABC 
AbC

4、同时过滤不同的字符串

[root@localhost ~]# grep -E 'abc|def' test1.txt 
abc def
habc

[root@localhost ~]# grep -Ei 'abc|def' test1.txt 
abc def
habc
ABC 
AbC

5、计算匹配的字符串数量

[root@localhost ~]# grep 'abc' test1.txt 
abc def
habc
[root@localhost ~]# grep -c 'abc' test1.txt 
2

[root@localhost ~]# grep -i 'abc' test1.txt 
abc def
habc
ABC 
AbC
[root@localhost ~]# grep -ci 'abc' test1.txt #不区分大小写匹配
4

6、只输出匹配的内容

[root@localhost ~]# grep -o 'abc' test1.txt 
abc
abc

7、只输出符合要求的单词

[root@localhost ~]# grep -w 'abc' test1.txt  #而不会出现habc这行
abc def

8、去掉文件中空行和以#号开头的行(这个可以在某些配置文件去掉相关注释查看核心的配置信息,如nginx.conf)

[root@localhost ~]# cat test2.txt  #文本信息
zhangsan

lisi


wangwu
#注释
wangermazi

#注释信息
#其他信息
liuxing
#其他信息
xixihaha #注释信息
[root@localhost ~]# grep -E '^$' test2.txt #这里只查询空行




[root@localhost ~]# grep -E '^$|#' test2.txt #这里查询空行和带有#号的行



#注释

#注释信息
#其他信息
#其他信息
xixihaha #注释信息
[root@localhost ~]# grep -E '^$|^#' test2.txt #这里查询空行和行首带有#号的行



#注释

#注释信息
#其他信息
#其他信息
[root@localhost ~]# grep -Ev '^$|^#' test2.txt  #使用-v参数排除,则是最终剩下的有用信息
zhangsan
lisi
wangwu
wangermazi
liuxing
xixihaha #注释信息