grep 全名 Global Regular Expression Print,意為「全域正規表達式版本」,所有使用者都能使用。它在一個或多個檔案中搜尋樣式,把命中的行送到標準輸出,不會更動原檔。
它在 shell 腳本中格外好用,因為 grep 會用回傳值表達結果:找到回傳 0,沒找到回傳 1,檔案不存在回傳 2,於是就能拿來做流程判斷。
grep [option] pattern file
-a 不忽略二進位資料。
-A<n> 除命中外,另顯示後 n 行。
-B<n> 另顯示前 n 行。
-C<n> 前後各顯示 n 行。
-b 標示命中行首字元的位元組編號。
-c 只輸出命中行數。
-d 指定搜尋目錄時的動作。
-e 指定比對樣式。
-E 使用延伸正規表達式。
-F 視為固定字串。
-G 使用基本正規表達式。
-f<檔案> 從檔案讀取多組樣式,每行一條。
-h 不顯示檔名。
-H 顯示檔名。
-i 忽略大小寫。
-l 只列出命中的檔名。
-L 只列出未命中的檔名。
-n 標示行號。
-q 安靜模式,不輸出任何內容。
-r 遞迴搜尋。
-s 不顯示錯誤訊息。
-v 反向選取,顯示未命中的行。
-w 全字比對。
-x 全行比對。
-y 同 -i。
^ 錨定行首,'^grep' 匹配以 grep 開頭的行。
$ 錨定行尾,'grep$' 匹配以 grep 結尾的行。
. 匹配任一非換行字元,'gr.p'。
* 重複前一個字元零到多次。
[] 字元集合,'[Gg]rep' 同時匹配 Grep 與 grep。
[^] 排除集合,'[^A-FH-Z]rep'。
\(..\) 標記群組。
\</\> 錨定單字起訖。
x\{m\}/x\{m,\}/x\{m,n\} 重複次數區間。
\w 文字與數字字元,\W 反之。
\b 單字邊界,'\bgrep\b' 只匹配 grep 這個字。
為跨國字元編碼一致,POSIX 定義了 [:alnum:]、[:alpha:]、[:digit:]、[:lower:]、[:upper:]、[:space:]、[:punct:]、[:cntrl:]、[:print:]、[:graph:]、[:xdigit:] 等類別,必須放在 [] 內才會生效,例如 [[:alnum:]]。
ps -ef | grep svn root 4943 1 0 Dec05 ? 00:00:00 svnserve -d -r /opt/svndata/grape/ root 16867 16838 0 19:53 pts/0 00:00:00 grep svn
第二列是 grep 自己,並非真正要找的目標。想排除它:
ps aux | grep ssh | grep -v "grep" ps aux | grep '[s]sh' # 用字元集合技巧讓自己不被匹配
ps -ef | grep svn -c
cat test.txt | grep -f test2.txt cat test.txt | grep -nf test2.txt # 同時顯示行號
grep -n 'linux' test.txt test2.txt test.txt:1:hnlinux test2.txt:1:linux
cat test.txt | grep '^u' # 以 u 開頭 cat test.txt | grep '^[^u]' # 不以 u 開頭 cat test.txt | grep 'hat$' # 以 hat 結尾 cat test.txt | grep -E "ed|at" # 使用延伸正規表達式做或運算
grep '[a-z]\{7\}' *.txt # 至少 7 個連續小寫字母