shell四劍客之grep

grep的基本格式
grep -[參數] ‘word’ filename

演示案例
head -n 10 /etc/passwd > grep.txt
grep --color 'root' grep.txt    在匹配的內容裏,root字樣會顯示顏色

-v 反向選擇

grep -v 'mail' grep.txt 不顯示包含mail的行

-n 顯示行號

grep -n 'uucp' grep.txt 顯示匹配uucp的行號

-c 顯示匹配的行數

grep -c 'sbin' grep.txt

-i 不區分大小寫

echo "MAIL" >> grep.txt
grep -i 'mail' grep.txt     大寫小寫的mail都會匹配

-w 精確匹配

grep -w 'bin' grep.txt  此時包含sbin的行不會被查找
grep '\<bin\>' grep.txt 格式\< \>與-w效果一樣
grep --color -n -w 'bin' grep.txt

-l和-L -l是一次搜索多個文件,找出指定字符的文件,-L反向選擇

[root@localhost four]# grep -l 'bin' *.txt  包含bin的文件名
grep.txt
sed.txt
[root@localhost four]# ls
awk.txt  grep.txt  sedcommand  sed.txt
[root@localhost four]# grep -L 'bin' *.txt  不包含bin的文件名
awk.txt

grep的正則表達
基本正則表達式(BRE):*,^,$,.,[,]
擴展正則表達式(ERE):?,+,|,(,),{,}

grep 'spo*l' grep.txt   *表0個或者是多個o,也就是匹配*前面的字符
grep '^sync' grep.txt   查找以sync爲首的行
grep 'bash$' grep.txt  查找末尾爲bash的行
grep 'b.n' grep.txt 符號.代表任意一個字符
grep 'ba[shd]h' grep.txt    匹配[]裏的任意一個字符,包括bash/bahh/badh
grep --color -n '[^b]in' grep.txt   匹配in前面不是b的行,即使是包含了bin,比如某行裏有bin,nologin,也會顯示。
grep -n '^[a-z]' grep.txt   以小寫字母開頭的行
grep '^[^a-zA-Z]' grep.txt  不以字母開頭的行,[]裏面的^代表反向選擇,在[]代表開頭
grep -n '\*$' grep.txt 以*爲末尾的行,需要轉義
grep -E 'MAIL|shutdown' grep.txt    多條件查找,符號|代表或
grep -v '^$' grep.txt  不顯示空格
grep -v '^$' grep.txt | grep -v '^#'   不顯示空格和註釋
grep '12.*56' grep.txt  .*表示匹配任何字符,包括空
grep 'spo\{2,\}' grep.txt   匹配2個或以上的o,{2,3}表示2-3個前面的字符,{2}代表剛好2個前面的字符
grep -E 'spo{2,}' grep.txt 與上面效果一樣

-A after,除了顯示匹配行,還會顯示該行下面的內容

grep -A 1 'mail' grep.txt

-B before,除了顯示匹配行,還會顯示該行上面的內容

grep -B 1 'mail' grep.txt

-C -A和-B同時顯示

grep -C 1 'mail' grep.txt
grep -n '[^[:lower:]]:root' grep.txt    非字母
grep -n '^[[:lower:]]' grep.txt 字母開頭
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章