grep (缩写来自Globally search a Regular Expression and Print)是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来。Unix的grep家族包括grep、egrep和fgrep。
grep的工作方式是这样的,它在一个或多个文件中搜索字符串模板。如果模板包括空格,则必须被引用,模板后的所有字符串被看作文件名。搜索的结果被送到标准输出,不影响原文件内容。
1.命令格式:
grep [option] pattern file
2.命令功能:
用于过滤/搜索的特定字符。可使用正则表达式能多种命令配合使用,使用上十分灵活 。
3.命令参数:
-a –text #不要忽略二进制的数据。
-A<显示行数> –after-context=<显示行数> #除了显示符合范本样式的那一列之外,并显示该行之后的内容。
-b –byte-offset #在显示符合样式的那一行之前,标示出该行第一个字符的编号。
-B<显示行数> –before-context=<显示行数> #除了显示符合样式的那一行之外,并显示该行之前的内容。
-c –count #计算符合样式的列数。
-C<显示行数> –context=<显示行数>或-<显示行数> #除了显示符合样式的那一行之外,并显示该行之前后的内容。
-d <动作> –directories=<动作> #当指定要查找的是目录而非文件时,必须使用这项参数,否则grep指令将回报信息并停止动作。
-e<范本样式> –regexp=<范本样式> #指定字符串做为查找文件内容的样式。
-E –extended-regexp #将样式为延伸的普通表示法来使用。
-f<规则文件> –file=<规则文件> #指定规则文件,其内容含有一个或多个规则样式,让grep查找符合规则条件的文件内容,格式为每行一个规则样式。
-F –fixed-regexp #将样式视为固定字符串的列表。
-G –basic-regexp #将样式视为普通的表示法来使用。
-h –no-filename #在显示符合样式的那一行之前,不标示该行所属的文件名称。
-H –with-filename #在显示符合样式的那一行之前,表示该行所属的文件名称。
-i –ignore-case #忽略字符大小写的差别。
-l –file-with-matches #列出文件内容符合指定的样式的文件名称。
-L –files-without-match #列出文件内容不符合指定的样式的文件名称。
-n –line-number #在显示符合样式的那一行之前,标示出该行的列数编号。
-q –quiet或–silent #不显示任何信息。
-r –recursive #此参数的效果和指定“-d recurse”参数相同。
-s –no-messages #不显示错误信息。
-v –revert-match #显示不包含匹配文本的所有行。
-V –version #显示版本信息。
-w –word-regexp #只显示全字符合的列。
-x –line-regexp #只显示全列符合的列。
-y #此参数的效果和指定“-i”参数相同。
4.使用实例
案例1:精确的匹配
[root@localhost ~]# cat .txt | grep all
all tooall
to alltoall all
allto100
uuualltoall
[root@localhost ~]# cat .txt | grep -w "all"
all tooall
to alltoall all
[root@localhost ~]#
案例2:加入自动颜色
[root@localhost ~]# cat .txt | grep -w "all" --color=auto
all tooall
to alltoall all
案例3 :取反参数 -v 选项
[root@localhost ~]# ps -ef | grep ssh
root : ? :: /usr/sbin/sshd
root : ? :: sshd: root@pts/
root : pts/ :: grep ssh
[root@localhost ~]# ps -ef | grep ssh | grep -v grep
root : ? :: /usr/sbin/sshd
root : ? :: sshd: root@pts/
[root@localhost ~]#
案例4 :统计出现的次数
[root@localhost ~]# grep -c "all" .txt[root@localhost ~]#
案例5:显示匹配的行数
[root@localhost ~]# grep -n "all" .txt
:all tooall
:to alltoall all
:allto100
:uuualltoal
案例6:显示匹配的文件
[root@localhost ~]# grep "all" .txt .txt .txt
.txt:all tooall
.txt:to alltoall all
.txt:allto100
.txt:uuualltoall
.txt:alltohell .txt
.txt:allheot4.txt
[root@localhost ~]# grep -l "all" .txt .txt .txt
.txt
.txt
.tx
案例7:忽略字符大小写
[root@localhost ~]# cat .txt | grep -i "ALL"
all tooall
ALAALLL
to alltoall all
allto100
uuualltoall
案例8:打印出匹配文本之前或者之后的行