grep

-i 不区分大小写

-c 统计匹配的次数

-m指定匹配的结果数(例如:-m 1  相当于head -n1)

-n 显示过滤的结果在原文中的行号

-w 精确匹配

\b 匹配单词边界  --eg2:

\s 单个空格字符

-o 只输出匹配的内容

--color=auto 给过滤的结果添加颜色 (可以用alias做成别名)

-v 取反,排除匹配的内容

-A n :After的意思,显示匹配字符串后n行的数据

-B n :Befor的意思,显示匹配字符串前n行的数据

-C n :显示前后的各n行

-rl 在目录下面查找关键字

eg:grep -rl config /etc/puppet/modules

-E 支持扩展的正则表达式,可以同时过滤多个   grep -E 等价于 egrep  -eg1

eg1:

[root@90-99 oldboy]# chkconfig --list | grep "3:on" | wc -l
16
[root@90-99 oldboy]# chkconfig --list | grep "3:on" | grep -vE "sshd|crond|rsyslog|network"
cobblerd        0:off   1:off   2:off   3:on    4:on    5:on    6:off
flume-ng        0:off   1:off   2:on    3:on    4:on    5:on    6:off
httpd           0:off   1:off   2:on    3:on    4:on    5:on    6:off
irqbalance      0:off   1:off   2:off   3:on    4:on    5:on    6:off
mysqld          0:off   1:off   2:on    3:on    4:on    5:on    6:off
rabbitmq-server 0:off   1:off   2:on    3:on    4:on    5:on    6:off
redis           0:off   1:off   2:on    3:on    4:on    5:on    6:off
sendmail        0:off   1:off   2:on    3:on    4:on    5:on    6:off
snmpd           0:off   1:off   2:on    3:on    4:on    5:on    6:off
tog-pegasus     0:off   1:off   2:off   3:on    4:off   5:on    6:off
xinetd          0:off   1:off   2:off   3:on    4:on    5:on    6:off
zabbix-agent    0:off   1:off   2:on    3:on    4:on    5:on    6:off
[root@90-99 oldboy]# chkconfig --list | grep "3:on" | grep -vE "sshd|crond|rsyslog|network" | wc -l
12

eg2:

[root@robin oldboy]# cat a.txt 
abc
abcd
abcdfer
abcdfslfjasefkj
[root@robin oldboy]# grep "abc" a.txt   
abc
abcd
abcdfer
abcdfslfjasefkj
[root@robin oldboy]# grep "abc\b" a.txt        
abc


案例使用grep只过滤出ip地址

root@dx-it-tw07:/tmp# head 2017041214-log 

[12/Apr/2017:14:00:00 +0800] - - 10.32.39.119 GET GET /status HTTP/1.0 19 200 http-nio-8090-exec-107

root@dx-it-tw07:/tmp# 

root@dx-it-tw07:/tmp# head 2017041214-log  | grep -Po "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" 

10.32.39.119






      本文转自Tenderrain 51CTO博客,原文链接:http://blog.51cto.com/tenderrain/1613518,如需转载请自行联系原作者