首页 > 系统服务 > 详细

shell脚本--内容查找之grep命令

时间:2018-01-21 00:42:32      阅读:206      评论:0      收藏:0      [点我收藏+]

grep命令可以检索文件中包含关键字(可以使用正则)的行,默认区分大小写。

ubuntu@ubuntu:~/test$ cat test.txt
this is linux
this is Linux
this is mysql
this is Mysql
ubuntu@ubuntu:~/test$ grep ‘linux‘ test.txt
this is linux
ubuntu@ubuntu:~/test$ grep ‘Mysql‘ test.txt
this is Mysql
ubuntu@ubuntu:~/test$ 

  

使用 -c 参数,获取包含关键字的行数

ubuntu@ubuntu:~/test$ grep -c ‘is‘ test.txt
4
ubuntu@ubuntu:~/test$ grep -c ‘sql‘ test.txt
2
ubuntu@ubuntu:~/test$ 

 

使用 -n 参数,打印内容的同时,显示所在的行号

ubuntu@ubuntu:~/test$ cat test.txt
this is linux
this is Linux
this is mysql
this is Mysql
ubuntu@ubuntu:~/test$ grep -n ‘mysql‘ test.txt
3:this is mysql
ubuntu@ubuntu:~/test$ 

  

使用 -i 参数,查找时,不区分大小写

ubuntu@ubuntu:~/test$ grep -i ‘mysql‘ test.txt
this is mysql
this is Mysql
ubuntu@ubuntu:~/test$ 

  

使用 -v 参数,查找不包含关键字的行

ubuntu@ubuntu:~/test$ cat test.txt
this is linux
this is Linux
this is mysql
this is Mysql
ubuntu@ubuntu:~/test$ grep -v ‘Linux‘ test.txt
this is linux
this is mysql
this is Mysql
ubuntu@ubuntu:~/test$ 

  

要想使用正则表达式,可以使用 -E 参数

shell正则和perl语言的正则类似,基本通用。

ubuntu@ubuntu:~/test$ cat test.txt
this is linux
this is Linux
that are apples
ubuntu@ubuntu:~/test$ grep -E ‘^that‘ test.txt #以that开头的行
that are apples
ubuntu@ubuntu:~/test$ grep -E ‘Linux$‘ test.txt #以Linux结尾的行
this is Linux
ubuntu@ubuntu:~/test$ grep -E ‘.inux‘ test.txt # ‘.‘表示任意一个字符(不包含空白)
this is linux
this is Linux
ubuntu@ubuntu:~/test$ grep -E ‘p*‘ test.txt  # ‘*’表示前面一个字母出现0,1或任意多次
this is linux
this is Linux
that are apples
ubuntu@ubuntu:~/test$ grep -E ‘.+p.+‘ test.txt # ‘+’表示前面一个字母出现1或任意多次
that are apples
that are apples
ubuntu@ubuntu:~/test$ grep -E ‘p{2}‘ test.txt # {n}前面的一个字符出现n次
that are apples
ubuntu@ubuntu:~/test$ 

  还有一些常用的匹配模式,比如 ‘^$‘表示一个空行 ;   ‘^.$‘表示只有一个字符的行  ; 使用 \ 来转义,比如使用\.来匹配一个点   ; [0-9]表示匹配一个数字 ; [a-z]|[A-Z]表示任意一个字母; 使用|表示‘或’  ;

ubuntu@ubuntu:~/test$ echo ‘ip is 192.168.1.1‘ > test.txt
ubuntu@ubuntu:~/test$ grep -E ‘([1-9][0-9]*\.){3}[1-9][0-9]*‘ test.txt
ip is 192.168.1.1
ubuntu@ubuntu:~/test$ 

  

 

  

shell脚本--内容查找之grep命令

原文:https://www.cnblogs.com/-beyond/p/8322317.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!