【图文解析 】高级文本处理命令-grep(文本编辑器)

grep(文本生成器)

grep是一种强大的文本搜索工具,他能使用正则表达式搜索文本,并把匹配的行统计出来

 

命令:grep [选项] [–color=auto] ”搜索字符串” filename

常用参数:

-c:统计符合条件的字符串出现的总行数。 (count)

-E:支持扩展正则表达式。 (expression)

-i:忽略字符大小写。 (ignore)

-n:在显示匹配到的字符串前面加上行号。 (number)

-v:显示没有”搜索字符串”内容的那一行。 (view)

-l:列出文件内容中有搜索字符串的文件名称。 (list)

-o:只输出文件中匹配到的部分。 (out)

-color=auto:将匹配到的字符串高亮出来。

 

1、基本使用

查询包含hadoop的行

grep hadoop /etc/passwd

[root@localhost ~]# grep hadoop /etc/passwd

hadoop:x:500:504:hadoop01:/home/hadoop:/bin/bash

 

grep huangbo  ./*.txt  ## 寻找当前路径下所有txt当中内容那些是带了huangbo字符串的

[root@localhost ~]# grep huangbo ./*.txt

./mazhonghua.txt:my name is huangbo is is huangbo                                

./sutdent.txt:huangbo 18 jiangxi                                               

 

2、先看一份数据:grep.txt

huangbo is shuaige

huangxiaoming is shuaige

liuyifei is meinv

hello world hello tom hello kitty

 

#how old are you

#one two three four five six seven eight nine ten

 

2.1、统计出现某个字符串的行的总行数

grep -c 'hello' grep.txt

grep -c 'is' grep.txt                                                        

[hadoop@hadoop04 ~]# grep -c 'hello' grep.txt

[hadoop@hadoop04 ~]# grep -c 'is' grep.txt

 

2.2、查询不包含is的行

grep -v 'is' grep.txt

[hadoop@hadoop04 ~]# grep -v 'is' grep.txt

 

2.3、正则表达包含huang

grep '.*huang.*' grep.txt

[hadoop@hadoop04 ~]# grep '.*huang.*' grep.txt

 

2.4、输出匹配行的前后N行(会包括匹配行)

使用-A参数输出匹配行的后一行:grep -A 1 "huangxiaoming" grep.txt

使用-B参数输出匹配行的前一行:grep -B 1 "huangxiaoming" grep.txt

使用-C参数输出匹配行的前后各一行:grep -C 1 "huangxiaoming" grep.txt

 

3、正则表达(点代表任意一个字符)

grep 'h.*p' /etc/passwd

 

4、正则表达以hadoop开头

grep '^hadoop' /etc/passwd

 

5、正则表达以hadoop结尾

grep 'hadoop$' /etc/passwd

 

以h或r开头的

grep '^[hr]' /etc/passwd

 

不是以h和r开头的

grep '^[^hr]' /etc/passwd

 

不是以h到r开头的

grep '^[^h-r]' /etc/passwd

 

正则表达式的简单规则:

.  : 任意一个字符

a* : 任意多个a(零个或多个a)

a? : 零个或一个a

a+ : 一个或多个a

.* : 任意多个任意字符

\. : 转义.

o\{2\} : o重复两次

[A-Z]

[ABC]

 

查找不是以#开头的行

grep -v '^#' grep.txt | grep -v '^$'      

[root@localhost ~]# grep -v '^#' grep.txt                  

 

[root@localhost ~]# grep -v '^#' grep.txt | grep -v '^$'

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值