grep讲解

1710人浏览 / 0人评论

一、grep简单讲解

  Linux系统中grep命令是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来。grep全称是Global Regular Expression Print,表示全局正则表达式版本,它的使用权限是所有用户。
  grep家族包括grep、egrep和fgrep。egrep和fgrep的命令只跟grep有很小不同。egrep是grep的扩展,支持更多的re元字符, fgrep就是fixed grep或fast grep,它们把所有的字母都看作单词,也就是说,正则表达式中的元字符表示回其自身的字面意义,不再特殊。linux使用GNU版本的grep。它功能更强,可以通过-G、-E、-F命令行选项来使用egrep和fgrep的功能。

二、grep参数

-v(取反)
 -n------(显示过滤过的行号)
 -i---------(不分大小写)
-w----------(按单词查找)
-o---------(只显示匹配到的内容)
A---------(显示匹配到的东西及后几行)
-B----------(显示匹配到的东西及前几行)
-C----------(显示配到的东西及前几行和后几行)
-c---------------(统计行数)
-l ----------------(显示文件文件名)
三、grep实战

1、过滤出以m开头的行

grep "^m" test.txt

2、过滤出以m结尾的行

grep "m$" test.txt 

3、排除空行并打印行号

grep -vn "^$"  test.txt

4、排除空行和以#开头的行并打印行号

grep -vn "^$|^#" /etc/nginx/nginx.conf  

5、匹配任意一个字符,不包括空行。(这个也是排除空行的一种,因为行号是一个字符都没有的)

grep "." test.txt

6、匹配所有

grep ".*" test.txt

7、匹配任意一个字符

grep "ng.nx" /etc/nginx/nginx.conf

8、匹配以点结尾的(利用撬棍) 

grep "\.$" test.txt

9、精准匹配 (只显示匹配到的内容)

[root@1 home]# grep -o nginx  /etc/nginx/nginx.conf 
nginx
nginx
nginx
nginx
nginx
[root@1 home]# grep  nginx  /etc/nginx/nginx.conf 
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;
    include       /etc/nginx/mime.types;
    access_log  /var/log/nginx/access.log  main;
    include /etc/nginx/conf.d/*.conf;
 

10、 匹配包含任意n g i n x的行

grep "[nginx]" /etc/nginx/nginx.conf

11、匹配范围是1-9的行

grep "[1-9]"  test.txt

##匹配a-z的行

grep "[a-z]"  test.txt

##匹配a-z的行并且不区分大小写

grep "[a-Z]"  test.txt

 12、匹配w重复了3次的行

grep "w\{3\}" /etc/nginx/nginx.conf

14、匹配重复的w   3-5次的行

 grep -E "w{3.5}" /etc/nginx/nginx.conf

 15、匹配w至少一次或者一次以上的

grep -E "8{1,}" test.txt

 16、匹配mysql并且不区分大小写

grep -i "mysql" test.txt

17、只匹配mysql单词的,amysql   mysqls amysqld  这种的不匹配

grep -w "mysql" test.txt

 18、显示匹配error的后3行

grep -A 3 "error" /var/log/messges

19、显示匹配error的上3行

 grep -B 3 "error" /var/log/messges

20、显示匹配error的上3行和下3行

 grep -C 3 "error" /var/log/messges

21、显示文件中匹配error的一共多少行

grep -c "error" /var/log/messges

22、只显示哪些文件中包含了nginx

[root@1 home]# grep -l nginx /etc/nginx/*
/etc/nginx/fastcgi_params
/etc/nginx/koi-utf
/etc/nginx/nginx.conf

 23、查询/etc/nginx/目录下哪些文件包含了nginx,并且目录下的目录下查看

[root@1 home]# grep -lR nginx /etc/nginx/*
/etc/nginx/conf.d/.youxi.conf.swp
/etc/nginx/conf.d/default.conf.bak
/etc/nginx/fastcgi_params
/etc/nginx/koi-utf
/etc/nginx/nginx.conf
/etc/nginx/win-utf

全部评论