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 是文本處理利器,掌握其正則表達式、上下文控制、反向匹配、遞歸搜索等高級用法,能將日誌分析、代碼搜索效率提升數倍。本文從面試題切入,通過大量實例演示 grep 核心技巧。

基礎用法對比

# 三種等效寫法
grep CPU: /var/run/dmesg.boot
cat /var/run/dmesg.boot | grep CPU:
< /var/run/dmesg.boot grep CPU:

統計匹配行數

grep WARNING /var/run/dmesg.boot -c   # 內建計數
grep WARNING /var/run/dmesg.boot | wc -l  # 管道組合

核心選項實戰

選項功能示例
-w整詞匹配grep -w 'seven' file
-C n顯示匹配行前後 n 行grep -C 1 'keyword' file
-A n / -B n僅顯示後 n 行 / 前 n 行grep -A 2 'error' log
-v反向匹配(排除)grep -v '^#' config
-E擴展正則(支持 + ? {} () |)grep -E 'twenty[1-4]' file
-o僅輸出匹配部分grep -oE '\b\d{1,3}(\.\d{1,3}){3}\b' file
-r遞歸搜索目錄grep -rni 'allow' /usr/src/sys/dev/
-i忽略大小寫
-n顯示行號

正則表達式進階

  • 詞邊界:\<word(詞首),word\>(詞尾)
  • 行錨點:^pattern(行首),pattern$(行尾)
  • 字符類:[[:upper:]]、[[:digit:]]、[[:space:]] 等 POSIX 標準類
  • 反向引用:grep -E '(six|seven|eight).*\1' file(匹配重複詞)
  • 或邏輯:grep -E 'sock|ITEM' file 或 grep -E '(sock|ITEM)' file

實戰技巧

  1. 提取 IP 地址並去除註釋行:
    grep -v '#' /etc/resolv.conf | grep -oE '\b[0-9]{1,3}(\.[0-9]{1,3}){3}\b'
  2. 過濾 ps 輸出中的 grep 自身進程:
    ps -afx | grep '[t]tyv'   # 技巧:字符類讓自身不匹配
  3. 輸入真實 Tab 字符:Ctrl+V 後按 Tab → grep " 504 " file
  4. 高亮匹配:設置環境變量 GREP_COLORS 或使用 --color=auto

遞歸搜索源碼實例

grep -rni allow /usr/src/sys/dev/ | grep unsupp
# 快速定位 Intel 非標準 SFP 支持代碼
Copyright © Windows教程網 All Rights Reserved