分類:linux/Ubuntu
版權聲明:本文為博主(微博 @Gary 的影響力)原創文章,未經允許不得轉載。博客地址:https://garyelephant.me
grep 在一或多個檔案中搜尋與模式(pattern)相符的行並印出結果,不會修改原檔。語法:
$ grep [option(s)] pattern [file(s)]
-i 忽略大小寫:
$ grep -i hAL /etc/passwd
-w 只匹配整個單字:
$ grep -iw "samba" /etc/samba/smb.conf
-r 遞迴搜尋子目錄;-v 反向匹配,印出不包含模式的行。
控制輸出方式:
注意:選項區分大小寫;多個選項可合併,如 $ grep -iwr;grep 會回傳狀態值——找到為 0、找不到為 1、檔案不存在為 2,這讓它能被用在腳本的流程判斷中。
grep 使用「基本正則運算式」,若要更完整的語法可加 -E(等同 egrep)。以下字元具特殊意義:*, +, [, ], ^, $, \, {}
. 匹配任意單一字元X* 匹配 0 個或多個 X;X\+ 匹配 1 個以上[a-z]、[^a-z]、[0-9] 字元集合與其反集^hello 開頭為 hello;hello$ 結尾為 hello\ 跳脫,如 $ grep '\[' filename 才會真的去匹配左方括號,直接寫 [ 會得到 Invalid regular expression\d=[0-9]、\D=[^0-9]、\w=[A-Za-z0-9_]、\W 反集、\s 空白、\S 非空白、\b 單字邊界、\B 非邊界X\{n\} 連續 n 個 X;X\{n,\} 至少 n 個;X\{,m\} 最多 m 個;X\{n,m\} n 到 m 個最常見的錯誤是把 shell 的 . 與 * 和正則的搞混:正則中 . 像 shell 的 ?(任意單字元),而 * 表示前一個字元出現 0 次以上,跟 shell 的字元萬用意義完全不同。
OR 有四種寫法:
$ grep 'pattern1\|pattern2' filename
$ grep -E 'pattern1|pattern2' filename
$ egrep 'pattern1|pattern2' filename
$ grep -e pattern1 -e pattern2 filename
AND:
$ grep -E 'pattern1.*pattern2' filename
$ grep -E 'pattern1.*pattern2|pattern2.*pattern1' filename
$ grep -E 'pattern1' filename | grep -E 'pattern2'
NOT:
$ grep -v 'pattern' filename
$ grep -c "^$" filename # 統計空行數
$ grep ".*hello" filename # hello 前有任意字串
$ grep "hi \+hello" filename # hi 與 hello 間至少一個空白
$ grep "hi *hello" filename # 中間無空白或多個空白
$ grep "hi \?hello" filename # 中間無空白或恰好一個
$ grep "127\.0\.0\.1" filename # 匹配含特殊字元的 IP
$ ls --help | grep "dired" # 過濾其他命令的輸出
從 Apache 日誌中抓出以 IP 開頭且含 200 狀態碼的記錄:
$ grep -Eoc "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}.* 200" /srv/www/example.com/logs/access.log
參考資料包含 The Geek Stuff、Linode Library、CyberCiti 等網站的 grep 教學,以及 51CTO 的中文介紹。
轉載本文請註明作者與出處 [Gary 的影響力] https://garyelephant.me,請勿用於任何商業用途。作者:Gary Gao