Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux grep 命令完全指南:從入門到正則實戰

編輯:Linux 教學

核心定位

grep (Global Regular Expression Print) 是文本搜索利器,支援基本/擴展/Perl 正則,逐行匹配並輸出符合行。權限:所有用戶可用。

常用選項速查

正則表達式元字符對照(BRE vs ERE vs PCRE)

選項長選項說明
-i--ignore-case忽略大小寫
-v--invert-match反向匹配(輸出不匹配行)
-n--line-number顯示行號
-c--count僅輸出匹配行計數
-l--files-with-matches僅列出含匹配的檔案名
-L--files-without-match列出無匹配的檔案名
-r--recursive遞歸搜索子目錄
-d skip--directories=skip忽略目錄(避免 "Is a directory" 警告)
-w--word-regexp整詞匹配(邊界為非單詞字符)
-E--extended-regexp使用擴展正則(ERE),egrep 別名
-P--perl-regexp使用 Perl 正則(PCRE),功能最強
-A N--after-context=N顯示匹配行後 N 行
-B N--before-context=N顯示匹配行前 N 行
-C N--context=N顯示匹配行前後各 N 行
--color=auto高亮匹配部分(建議別名 alias grep='grep --color=auto')

實戰範例集

1. 基礎搜索

grep 'error' /var/log/messages                    # 簡單匹配
grep -i 'failed' *.log                            # 忽略大小寫
grep -n 'TODO' src/*.c                            # 顯示行號
grep -r 'FIXME' /project --include='*.py'         # 遞歸 + 檔案過濾

2. 正則進階

grep -E '^[[:space:]]*$' file                     # 空白行
grep -P '^\d{4}-\d{2}-\d{2}' logfile              # ISO 日期行 (PCRE)
grep -w 'root' /etc/passwd                        # 整詞匹配 root
grep -E '\<[A-Z]{3,}\>' file                      # 3 個以上大寫單詞
grep 'pattern1\|pattern2' file                    # 或 (BRE 需轉義)
grep -E 'pattern1|pattern2' file                  # 或 (ERE)
grep 'pattern1' file | grep 'pattern2'            # 且 (管道串聯)

3. 上下文與統計

grep -C 3 'panic' /var/log/kern.log               # 前後各 3 行
grep -c '^From:' mailbox                          # 郵件計數
grep -l 'TODO' *.c *.h                            # 列出含 TODO 的檔案

4. 實用組合拳

# 統計當前目錄下程式碼行數(排除空行、註釋)
grep -vE '^\s*$|^\s*#' *.py | wc -l

# 找出佔用磁碟最大的 10 個目錄
du -h --max-depth=1 | sort -hr | head

# 實時監控日誌關鍵字
tail -f /var/log/nginx/access.log | grep --line-buffered ' 50[0-9] '

效能提示

  • 固定字串搜索用 grep -F (fgrep),避免正則解析開銷。
  • 大檔案優先用 grep -m 1 只找首個匹配,或配合 awk/sed 流式處理。
  • 避免 grep . * 產生大量「Is a directory」輸出,加 -d skip 或 -r。

總結

掌握 -i -v -n -r -w -E -P -A/B/C --color 核心選項,熟悉 BRE/ERE/PCRE 差異,善用管道組合,即可應對 95% 文本搜索場景。複雜結構化數據建議改用 jq (JSON)、xq (XML)、awk (欄位)。

Copyright © Windows教程網 All Rights Reserved
功能BRE (預設)ERE (-E)PCRE (-P)
單字符...
零或多次***
一次或多次\+++
零或一次\???
分組捕獲\(\)()()
或\|||
行首^^^
行尾$$$
詞首\<\<\b
詞尾\>\>\b
反向引用\1\1\1