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 find 命令忽略指定目錄:-prune 參數完整用法與多目錄排除技巧

編輯:關於 Linux

find 搜尋時需排除特定子目錄(如 /proc、/sys、備份目錄),關鍵在 -prune 參數與邏輯組合。本文詳解單/多目錄排除、檔名過濾與內容搜尋組合。

核心語法

find 搜尋路徑 -path "排除路徑" -prune -o 條件 -print

關鍵規則:-path 必須緊跟在搜尋路徑之後,否則不生效。

單目錄排除

# 找 /home/zth 下所有檔案,排除 /home/zth/astetc
find /home/zth -path "/home/zth/astetc" -prune -o -type f -print

# 按檔名過濾
find /home/zth -path "/home/zth/astetc" -prune -o -type f -name "cdr_*.conf" -print

多目錄排除(括號分組)

find /home/zth \( -path "/home/zth/astetc" -o -path "/home/zth/etc" \) -prune -o -type f -print

find /home/zth \( -path "/home/zth/astetc" -o -path "/home/zth/etc" \) -prune -o -type f -name "cdr_*.conf" -print

注意:\( \) 前後需有空格,shell 需轉義或用引號包裹。

進階:配合 xargs 搜尋檔案內容

路徑含空格(安全寫法)

find . -name "mysql*" -print0 | xargs -0 grep "SELECT lead_id FROM vicidial_list where vendor_lead_code"

路徑無空格

find . -name "mysql*" | xargs grep "SELECT lead_id FROM vicidial_list where vendor_lead_code"

-print0 + xargs -0 以 null 字元分隔,完美處理特殊字元檔名。

常見錯誤避坑

  • -prune 位置錯誤 → 排除失效
  • 忘記 -o 邏輯或 → 後續條件不執行
  • 多目錄未用括號分組 → 優先級錯誤
  • 直接 xargs 不加 -0 → 空格檔名斷裂

速查模板

# 排除目錄 A、B,找所有檔案
find /path \( -path "/path/A" -o -path "/path/B" \) -prune -o -type f -print

# 排除目錄,按名稱找檔
find /path \( -path "/path/A" -o -path "/path/B" \) -prune -o -type f -name "pattern" -print

# 排除目錄,搜尋內容
find /path \( -path "/path/A" -o -path "/path/B" \) -prune -o -type f -name "*.log" -print0 | xargs -0 grep "keyword"

熟練 -prune 組合拳,能精準鎖定搜尋範圍,避免掃描無關目錄浪費時間。

Copyright © Windows教程網 All Rights Reserved