一、grep的优点和缺点:

优点:1.grep用来取行,简单方便

      2.单纯从文本中搜索内容,grep的速度是最快的。有人做过测试,从一个

        200w+的文件中搜索内容,grep用了2s,sed用了20s,awk用了73s

      3.grep支持正则表达式。sed和awk也支持正则表达式

缺点:更多需要配合cut、sed和awk完成


二、grep的常用参数:

1.-v取反

2.-n显示行号

3.-c统计文件有几行

4.-w只匹配的XX行

5.-w -c统计只匹配的XX的有几行

6.-i不区分大小写

7.-A after的意思

8.-B before的意思

9.-C centre的意思


三、简单介绍grep的用法:

  1. 只查找vsftpd的进程信息

[root@localhost ~]#ps -ef |grep vsftp |grep -v grep 

root      2295     1  0 Jan22 ?        00:00:00 /usr/sbin/vsftpd /etc/vsftpd/vsftpd.conf


2.显示行号,查找的sync在第6行

[root@localhost ~]# grep -n 'sync' /etc/passwd

6:sync:x:5:0:sync:/sbin:/bin/sync


3.查找匹配bash的有4行

[root@localhost ~]# grep  -c 'bash' /etc/passwd

4

[root@localhost ~]# grep -c . /etc/passwd

31


4.查找只匹配bash的行

[root@localhost ~]# grep  -w 'bash' /etc/passwd

root:x:0:0:root:/root:/bin/bash

postgres:x:26:26:PostgreSQL Server:/var/lib/pgsql:/bin/bash

mysql:x:27:27:MySQL Server:/var/lib/mysql:/bin/bash

oracle:x:500:501::/home/oracle:/bin/bash


5.[root@localhost ~]#grep  -w -c 'bash' /etc/passwd

4


6.把大小写的aa都查询出来了

[root@localhost ~]# grep  'aa' greptest.txt 

aa

aaa

aab

[root@localhost ~]# grep  -i 'aa' greptest.txt 

aa

aaa

aab

AA



7.打印以sync为中心的后两行

[root@localhost ~]# grep -n -A 2 'sync' /etc/passwd

6:sync:x:5:0:sync:/sbin:/bin/sync

7-shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown

8-halt:x:7:0:halt:/sbin:/sbin/halt


8.打印以sync为中心的前两行

[root@localhost ~]# grep -n -B 2 'sync' /etc/passwd

4-adm:x:3:4:adm:/var/adm:/sbin/nologin

5-lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

6:sync:x:5:0:sync:/sbin:/bin/sync


9.打印以sync为中心的前后两行

[root@localhost ~]# grep -n -C 2 'sync' /etc/passwd

4-adm:x:3:4:adm:/var/adm:/sbin/nologin

5-lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

6:sync:x:5:0:sync:/sbin:/bin/sync

7-shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown

8-halt:x:7:0:halt:/sbin:/sbin/halt


四、正则表达式:

正则表达式,需要用egrep

1..匹配一个字符

2.?匹配0个或者一个字符

3.* 匹配0到多个的任意字符

4.+ 匹配连续1到多个相同字符

5.{n}重复n次

6.{n,}重复连续字符2次或者2次以上

7.{n,m} 重复字符至少n次,最多m次

[] r[op]t匹配root ropt

\转义字符

^以什么开头

$以什么结尾


1.匹配一个字符

[root@localhost ~]# egrep ro.t greptest.txt

rott

rolt

root


2.匹配0个或者一个字符

[root@localhost ~]# egrep ro?t greptest.txt 

rt

rot

rott


3.匹配0个或者多个相同字符

[root@localhost ~]# egrep ro*t greptest.txt 

rt

rott

root

rooot

rot

roooot

rooooot


4.匹配连续1个或者多个相同字符

[root@localhost ~]# egrep ro+t greptest.txt 

rott

root

rooot

rot

roooot

rooooot


5.重复2次o

[root@localhost ~]# egrep ro{2}t greptest.txt 

root


6.重复2次以上,需要加双引号

[root@localhost ~]# egrep ro"{2,}"t greptest.txt 

root

rooot

roooot

rooooot


7.重复至少2次,最多3次

[root@localhost ~]# egrep ro"{2,3}"t greptest.txt 

root

rooot


8.grep和egrep的用法

[root@localhost ~]# egrep ro\{2,\}t greptest.txt

root

rooot

roooot

rooooot

[root@localhost ~]# grep 'ro\{2,\}t' greptest.txt 

root

rooot

roooot

rooooot