grep 文本过滤工具。


grep 命令是Linux系统中最重要的命令之一,其功能是从文本文件或管道数据流中筛选匹配的行和数据。

1、语法格式: grep [options 参数]	[pattern 匹配模式]  	[file 查找的文件]
	pattern 匹配模式,可以是普通的文字符号,也可以是正则表达式。
2、参数选项
	-v		显示不包含匹配文本的所有行(排除行)。
	-n		显示匹配的行和行号。
	-i		不区分大小写(只适用于单字符),默认情况下是区分大小写的。
	-c		只统计匹配的行数,不是匹配的次数。
	-o		只输出匹配的内容。
	-w		只匹配过滤的单词。
	-E		使用扩展egrep命令。
	--color=auto	为 grep 过滤的匹配字符串添加颜色。


[root@centos79 test]# cat grep.txt 
linux
sunwukong
zhubajie
Shaseng
tangseng

1、显示匹配行的行号。
[root@centos79 test]# grep -n "zhubajie" grep.txt 
3:zhubajie  ## 第三行
[root@centos79 test]# 

2、排除 'zhubajie' 这一行不显示。
[root@centos79 test]# grep -v "zhubajie" grep.txt 
linux
sunwukong
Shaseng
tangseng  ## 少了一行
[root@centos79 test]# 

3、显示所有的行号。'.' 表示匹配任意单个字符,即匹配所有的内容。
[root@centos79 test]# grep -n "." grep.txt 
1:linux
2:sunwukong
3:zhubajie
4:Shaseng
5:tangseng
[root@centos79 test]# 

4、不区分大小写匹配
[root@centos79 test]# grep "sha" grep.txt ## 由于Shaseng 首字母是大写,所以没有匹配出来。
[root@centos79 test]# grep -i "sha" grep.txt  ## -i 不区分大小写。
Shaseng
[root@centos79 test]# 

5、同时匹配多个字符。
[root@centos79 test]# grep "sun|zhu" grep.txt ## 匹配多个字符,需要使用扩展的 egrep
[root@centos79 test]# grep -E "sun|zhu" grep.txt  ## -E 参数可以实现
sunwukong
zhubajie
[root@centos79 test]# 

6、统计匹配到的行数。
[root@centos79 test]# grep -E "sun|zhu" grep.txt 
sunwukong
zhubajie
[root@centos79 test]# grep -Ec "sun|zhu" grep.txt  ## 只显示匹配到的行数。
2
[root@centos79 test]# 

7、只输出匹配到的内容。
[root@centos79 test]# grep "sun" grep.txt  ## 默认时,显示匹配到的行内容。
sunwukong
[root@centos79 test]# grep -o "sun" grep.txt  ## -o 参数,只显示匹配的内容。
sun
[root@centos79 test]# 

8、-w 只匹配过滤的单词
[root@centos79 test]# grep -w "zhu" grep.txt  ## 如果有 -w 参数就会只匹配 'zhu' 这一个单词,所以没有
[root@centos79 test]# grep -w "zhubajie" grep.txt 
zhubajie
[root@centos79 test]# 

grep 正则使用

## 文件内容
[root@centos79 test]# cat grep.txt 
linux
sunwukong
zhubajie
Shaseng

tangseng

bailongMa
## 过滤空行的文件或含有 'zhubajie' 的文件
[root@centos79 test]# grep "^$|zhubajie" grep.txt ## 匹配不到任何内容
##  -E 使用扩展egrep命令 '^$' 匹配空行。'|' 表示或的意思
[root@centos79 test]# grep -En "^$|zhubajie" grep.txt 
3:zhubajie
5:
7:
[root@centos79 test]# 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值