linux shell 腳本之深入淺出的grep的用法


   今天在糾結grep用法時候,由於講解的教材比較少,糾結了較長的時間。最終還是攻下了,所以拿出來給大家分享。

grep

      顯示匹配一個或多個模式的文本行,時常會作為管道后的第一步,以便對匹配上的數據做進一步處理。

最常見用法,查詢文件內字符串

[root@localhost /]# grep root /etc/shadow
root:$1$HFDnk5hm$DSAc4IUls1yUyocXFNQ.A.:15141:0:99999:7:::
[root@localhost /]#

參數

-E  使用擴展正則表達式進行匹配,使用grep –E 代替傳統的擴展正則表達式 egrep

擴展正則表達式和正則表達式的區別:  (-E選項的作用)

+  匹配一個或多個先前的字符

[root@localhost space]# touch test 

[root@localhost space]# vim test
aaaredhat
bbbredhat
yyyredhat
zzzredhat
redhataaa
redhatbbb
redhatyyy
redhatzzz
:wq

[root@localhost space]# cat test|grep –E '[a-h]+redhat'
aaaredhat
bbbredhat
[root@localhost space]#

[root@localhost space]# cat test|grep -E 'redhat+[h-z]'
redhatyyy
redhatzzz
[root@localhost space]#

當去掉-E選項的時候,正則表達式是不支持這樣查詢的。
[root@localhost space]# cat test|grep 'redhat+[a-z]'
[root@localhost space]#

?   匹配零個或多個先前的字符

[root@localhost space]# cat test|grep -E 'r?aaa'
aaaredhat
redhataaa
[root@localhost space]# cat test|grep 'r?aaa'
[root@localhost space]#

a|b|c  匹配a或b或c

[root@localhost space]# cat test|grep -E 'b|z'
bbbredhat
zzzredhat
redhatbbb
redhatzzz
[root@localhost space]# cat test|grep 'b|z'
[root@localhost space]#

() 分組符號

[root@localhost space]# cat test|grep -E 'redha(tz|ta)'
redhataaa
redhatzzz
[root@localhost space]# cat test|grep 'redha(tz|ta)'
[root@localhost space]#

x{m} 重復字符x,至少m次   (如果用正則表達式,格式為x\{m,\})

[root@localhost space]# cat test|grep -E 'a{3}'
aaaredhat
redhataaa
[root@localhost space]# cat test|grep 'a\{3,\}'
aaaredhat
redhataaa
[root@localhost space]#

-F  使用固定字符串進行匹配 grep –F 取代傳統的 fgrep 。 使用正則表達式; 默認情況下 grep 使用的就是正則表達式,grep = grep –F

-e  通常,第一個非選項的參數會指定要匹配的模式,這個模式以-號開頭時,grep就會混淆,而-e選項就將它確定為參數

[root@localhost space]# cat test|grep -e '-test'
-test
[root@localhost space]# cat test|grep '-test'
grep:無效選項 -- t
Usage: grep [OPTION]... PATTERN [FILE]...
Try `grep --help' for more information.
[root@localhost space]#

-i  模式匹配時,忽略大小寫

[root@localhost space]# cat test|grep -i test
-test
-TEST
[root@localhost space]#

-l  列出匹配模式的文件名稱  (列出當前目錄下含有test字符串的文件)

[root@localhost space]# grep -l 'test' ./*
./test
./test2
[root@localhost space]#

-q  靜默模式,如果匹配成功,則grep會離開,不顯示匹配。

[root@localhost space]# grep test ./test
-test
[root@localhost space]# grep -q test ./test
[root@localhost space]#

-s  不顯示錯誤信息

-v  顯示不匹配的項

[root@localhost space]# cat test|grep test
-test
[root@localhost space]# cat test|grep -v test
-TEST

[root@localhost space]#


免責聲明!

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



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