zl程序教程

您现在的位置是:首页 >  工具

当前栏目

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

命令shell -- 脚本 内容 查找 grep
2023-09-14 08:56:53 时间

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 参数,可以同时指定多个筛选条件

ubuntu@ubuntu:~$ cat test.txt 
this is a
this is b
three are a and b
ubuntu@ubuntu:~$ grep "a" test.txt | grep "this"   #与关系,包含a,并且包含this
this is a
ubuntu@ubuntu:~$ grep -e "a" -e "this" test.txt    #或关系,包含a或者包含this
this is a
this is b
three are a and b

 

要想使用正则表达式,可以使用 -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$