grep 全名是 global search regular expression(RE) and print out the line,也就是「全面搜尋正則表達式並把符合的行印出來」。它是 Linux 最強大的文本搜尋工具,能搭配正則表達式精準定位內容。
grep [選項]... PATTERN [FILE]...
功能是在每個 FILE 或標準輸入中查找 PATTERN。
先準備三個測試檔案 t1.txt、t2.txt、t3.txt。
[root@localhost grepDir]# grep "MenAngel" t1.txt t2.txt t3.txt t1.txt:I'm MenAngel!
[root@localhost grepDir]# grep -v "MenAngel" t1.txt t2.txt t3.txt
會印出所有「不含」MenAngel 的行。
[root@localhost grepDir]# grep "fight" t1.txt t2.txt t3.txt --color=auto t2.txt:Every one fights for a better future,but I fight for freedom!
[root@localhost grepDir]# grep -c "that" t1.txt t2.txt t3.txt t1.txt:1 t2.txt:0 t3.txt:2
[root@localhost grepDir]# grep -n "that" t1.txt t2.txt t3.txt
[root@localhost grepDir]# cat t1.txt t2.txt t3.txt | grep "MenAngel" I'm MenAngel!
[root@localhost grepDir]# cat t1.txt t2.txt t3.txt | grep ^I I'm MenAngel!
[root@localhost grepDir]# cat t1.txt t2.txt t3.txt | grep ^[^I]
[root@localhost grepDir]# seq 10 | grep "5" -A 3 5 6 7 8 [root@localhost grepDir]# seq 10 | grep "5" -B 3 2 3 4 5 [root@localhost grepDir]# seq 10 | grep "5" -C 3 2 3 4 5 6 7 8
多段命中時,各段之間會以 -- 作為分隔符。
[root@localhost grepDir]# echo this is a text line | grep -e "is" -e "line" -o is is line
[root@localhost grepDir]# echo MenAngel is sunjimeng | grep -f patfile MenAngel is sunjimeng
-r 遞迴搜尋目錄、-l 只印符合的檔名、-L 只印不符合的檔名、-w 全字比對、-x 整行完全匹配、-m NUM 命中指定次數後停止。另外 egrep 等同 grep -E,fgrep 等同 grep -F。
若 FILE 為 - 則讀取標準輸入;不帶 FILE 時讀取當前目錄(需搭配 -r)。有任何一行命中,退出碼為 0,否則為 1;發生錯誤且未指定 -q 時退出碼為 2,這在寫腳本判斷時很好用。
grep 的用法遠不止於此,累積更多實務經驗後再回來補充。