shell腳本--內容查找之grep命令


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$ 

  

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM