成功来自坚持,执着创造奇迹!

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

  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 1.txt | grep all
all tooall
to alltoall all
allto100
uuualltoall
[root@localhost ~]# cat 1.txt | grep -w "all"
all tooall
to alltoall all
[root@localhost ~]#

 

案例2:加入自动颜色

[root@localhost ~]# cat 1.txt | grep -w "all" --color=auto
all tooall
to alltoall all

 

案例3 :取反参数 -v 选项

[root@localhost ~]# ps -ef | grep ssh
root 2055 1 0 09:03 ? 00:00:00 /usr/sbin/sshd
root 24498 2055 0 11:21 ? 00:00:01 sshd: root@pts/0
root 24657 24502 0 12:11 pts/0 00:00:00 grep ssh
[root@localhost ~]# ps -ef | grep ssh | grep -v grep
root 2055 1 0 09:03 ? 00:00:00 /usr/sbin/sshd
root 24498 2055 0 11:21 ? 00:00:01 sshd: root@pts/0
[root@localhost ~]#

 

案例4 :统计出现的次数

[root@localhost ~]# grep -c "all" 1.txt
4
[root@localhost ~]#

 

案例5:显示匹配的行数

[root@localhost ~]# grep -n "all" 1.txt
1:all tooall
2:to alltoall all
3:allto100
4:uuualltoal

 

案例6:显示匹配的文件

[root@localhost ~]# grep "all" 1.txt 2.txt 4.txt
1.txt:all tooall
1.txt:to alltoall all
1.txt:allto100
1.txt:uuualltoall
2.txt:alltohell 2.txt
4.txt:allheot4.txt
[root@localhost ~]# grep -l "all" 1.txt 2.txt 4.txt
1.txt
2.txt
4.tx

 

案例7:忽略字符大小写

[root@localhost ~]# cat 1.txt | grep -i "ALL"
all tooall
ALAALLL
to alltoall all
allto100
uuualltoall

 

案例8:打印出匹配文本之前或者之后的行

 

posted on 2016-10-10 15:45  进击的魚骨  阅读(443)  评论(2编辑  收藏  举报