grep 全名 Global Search Regular Expression and Print,是 Linux 最核心的文字搜尋工具,支援正則表達式,能精準過濾檔案內容並輸出符合行。
grep [-acinv] [--color=auto] '搜尋字串' 檔案名
| 參數 | 功能 |
|---|---|
-a | 將二進位檔視為文字檔搜尋 |
-c | 僅統計符合行數 |
-i | 忽略大小寫 |
-n | 顯示行號 |
-v | 反向選擇(顯示不含字串的行) |
--color=auto | 關鍵字高亮顯色 |
server.properties 為例)# 1. 找出含 zookeeper 的行
grep 'zookeeper' server.properties
# 2. 高亮 + 顯示行號
grep -n --color=auto 'zookeeper' server.properties
# 3. 忽略大小寫 + 高亮 + 行號
grep -ni --color=auto 'zookeeper' server.properties
# 4. 統計出現次數(忽略大小寫)
grep -ci 'zookeeper' server.properties
# 5. 當前目錄遞迴搜尋含 zookeeper 的檔案
grep -r 'zookeeper' .
# 6. 僅列出符合的檔案名(不顯示內容)
grep -rl 'zookeeper' .
grep -E 'pattern1|pattern2' file 或 grep -e pattern1 -e pattern2 filegrep -w 'root' /etc/passwd(避免匹配到 rootfs 等)grep -A 3 -B 2 'error' logfile(顯示匹配行前 2 行、後 3 行)ps aux | grep nginx | grep -v grep(排除 grep 自身行)善用 grep 配合正則表達式,能讓日誌分析、程式碼審查、系統排錯事半功倍。下一篇將深入 awk、sed 進階文字處理。