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 與 xargs 進階實戰:高效檔案搜尋與批次處理

編輯:Linux 教學

find 指令核心語法

find 路徑 選項 [動作]

常用搜尋條件

選項功能範例
-name檔名比對 (支援萬用字元)-name "*.log"
-type檔案類型-type f (一般檔)、-type d (目錄)、-type l (符號連結)
-size檔案大小-size +100M、-size -10k、-size 512c (bytes)
-mtime修改時間 (天)-mtime -7 (7天內)、-mtime +30 (30天前)
-mmin修改時間 (分鐘)-mmin -60 (1小時內)
-user/-group擁有者/群組-user www
-perm權限比對-perm 644
-path路徑比對-path "*/cache/*"

時間參數詳細對照

參數存取時間狀態變更內容修改
分鐘-amin-cmin-mmin
天 (24小時)-atime-ctime-mtime

動作參數

  • -print:輸出路徑 (預設)
  • -exec cmd {} \;:對每個結果執行指令
  • -ok cmd {} \;:互動確認後執行
  • -delete:直接刪除 (謹慎使用)
  • -printf "format":自訂輸出格式

進階技巧

排除特定目錄

find /apps -path "/apps/bin" -prune -o -print

-prune 防止進入指定目錄,-o 代表邏輯 OR。

結合 xargs 批次處理

# 刪除 30 天前的 .log 檔案
find /var/log -name "*.log" -mtime +30 -print0 | xargs -0 rm -f

# 批次壓縮
find . -name "*.txt" -print0 | xargs -0 gzip

# 並行處理 (GNU xargs)
find . -name "*.jpg" -print0 | xargs -0 -P 4 -I {} convert {} -resize 50% {}

-print0 與 -0 處理含空白字元的檔名更安全。

邏輯運算子

find . \( -name "*.c" -o -name "*.h" \) -a -mtime -7  # 最近 7 天的 C/H 檔
find . ! -name "*.tmp"                                # 排除 .tmp 檔

實戰範例集錦

  1. 尋找大檔案:find / -type f -size +100M -exec ls -lh {} \;
  2. 清理暫存檔:find /tmp -type f -atime +3 -delete
  3. 尋找損壞符號連結:find . -xtype l
  4. 依權限搜尋:find . -type f ! -perm 644
  5. 統計程式碼行數:find . -name "*.py" -exec wc -l {} +

效能優化建議

  • 大範圍搜尋加上 -mount 避免跨檔案系統
  • 使用 -depth 先處理檔案再處理目錄 (配合 -delete)
  • 複雜條件用括號分組並轉義 \( \)
  • 定期更新 locate 資料庫 (updatedb) 進行快速檔名搜尋

熟練掌握 find 與 xargs,能將繁瑣的檔案管理工作自動化,是系統管理與開發運維的核心技能。

Copyright © Windows教程網 All Rights Reserved