Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Linux grep 指令完整教學:從基礎語法到正則表達式實戰範例

編輯:Linux 系統常見問題解答

grep 全名 Global Search Regular Expression and Print,是 Linux 最核心的文字搜尋工具,支援正則表達式,能精準過濾檔案內容並輸出符合行。

基本語法

grep [-acinv] [--color=auto] '搜尋字串' 檔案名

常用參數速查表

參數功能
-a將二進位檔視為文字檔搜尋
-c僅統計符合行數
-i忽略大小寫
-n顯示行號
-v反向選擇(顯示不含字串的行)
--color=auto關鍵字高亮顯色

實戰範例(以 Kafka 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 file
  • 整字匹配:grep -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 進階文字處理。

Copyright © Windows教程網 All Rights Reserved