grep 是 Linux 系統預裝的最強大文字模式搜尋工具。本文精選 12 個實戰範例,涵蓋套件查詢、設定檔過濾、檔案尋找、行號顯示、遞歸搜尋、精確匹配、壓縮檔搜尋、正則表達式等核心場景,助你從入門到精通。

# Debian/Ubuntu
sudo apt-get install grep
# RHEL/CentOS/Fedora
sudo yum install grep
dpkg -l | grep -i python
# -i 忽略大小寫 (grep 預設區分大小寫,養成加 -i 習慣)
輸出範例:
ii python2.7 2.7.3-0ubuntu3.4 Interactive high-level object-oriented language
ii python-openssl 0.12-1ubuntu2.1 Python wrapper around the OpenSSL library
grep -v '^#' /etc/apache2/sites-available/default-ssl
# -v 反向匹配:輸出**不包含**模式的行
# ^# 匹配行首為 # 的行 (較精確)
find . -name "*.mp3" | grep -i jayz | grep -vi remix
# 管線串聯多層過濾
ifconfig | grep -A 4 eth0 # 顯示匹配行及後 4 行 (After)
ifconfig | grep -B 2 UP # 顯示匹配行及前 2 行 (Before)
ifconfig | grep -C 2 lo # 顯示匹配行前後各 2 行 (Center)
記憶口訣:A=After、B=Before、C=Center
ifconfig | grep -c inet6
# 等同 grep ... | wc -l 但更高效
grep -n "main" setup.py
# 輸出: 10:def main():
grep -r "function" *
# 當前目錄及所有子目錄搜尋 "function"
ifconfig | grep -w "RUNNING" # 僅匹配完整單詞 RUNNING
ifconfig | grep -w "RUN" # 無輸出 (RUN 非獨立單詞)
zgrep -i error /var/log/syslog.2.gz
# 直接搜尋 .gz 檔案,無需先解壓
grep -E 'pattern1|pattern2' file # 或邏輯
egrep '^\s*(if|while|for)\b' *.c # C 語言關鍵字搜尋
# 支援 + ? | () 等擴展元字元
fgrep -f patterns.txt target.txt
# patterns.txt 每行一個模式,fgrep 逐行固定字串匹配 (無正則解析,速度極快)
grep -rn -C 3 -w "TODO" --include="*.py" --include="*.js" .
# -r 遞歸 -n 行號 -C 3 前後3行 -w 精確單詞 --include 限定副檔名
export GREP_OPTIONS='--color=auto' (已棄用) → 建議 alias grep='grep --color=auto'grep -r --exclude-dir=.git --exclude-dir=node_modules pattern .grep -l pattern *.txtgrep -q pattern file && echo "found"grep 是文字處理的瑞士刀,熟練掌握這 12 大場景與參數組合,能解決 90% 以上的搜尋過濾需求。