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 '^$'
|