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 命令詳解:從語法到實戰範例全掌握

編輯:Linux 教學

find 是 Linux 最強大的檔案搜尋工具,功能遠超 Windows 搜尋。本文系統梳理語法、邏輯運算、常用選項與實戰範例。

基本語法

find [起始目錄] [尋找條件] [操作]
# 等價於
find PATH OPTION [-exec COMMAND {} \;]

find 從起始目錄遞迴遍歷子目錄,根據條件匹配檔案。

邏輯運算符組合條件

運算符參數含義範例
AND-a預設,所有條件皆滿足find -name 'tmp' -a -type f -a -user 'inin'
OR-o任一條件滿足即可find -name 'tmp' -o -name 'mina*'
NOT!取反find ! -name 'tmp'

多條件組合時建議用括號 \( ... \),括號前需加反斜線轉義防止 Shell 誤解。

常用尋找條件選項

  • -name 'pattern':檔名匹配(支援 * ? [])
  • -type x:檔案類型(f 普通、d 目錄、l 符號連結、b/c 區塊/字元裝置、p FIFO、s socket)
  • -size n[bckw]:大小(b=512B 區塊、c=Byte、k=KiB、w=2Byte 字)
  • -user/-group/-uid/-gid:擁有者/群組
  • -perm mode:權限(如 644、755)
  • -mtime/-atime/-ctime n:修改/存取/狀態變更時間(天),+n 超過 n 天,-n 少於 n 天
  • -mmin/-amin/-cmin n:分鐘級時間條件
  • -path 'pattern':路徑匹配
  • -empty:空檔案/目錄

執行動作:-exec

find / -name "test-find.c" -type f -mtime +3 -user greek -prune /root/bin -exec rm {} \;
  • {} 代表匹配到的檔案路徑。
  • \; 結束標記,{} 與 \; 之間必須有空格。
  • -prune 排除目錄(例中排除 /root/bin)。

經典實戰範例

# 1. 顯示當前目錄下所有 main* 開頭檔案內容
find . -name 'main*' -exec more {} \;

# 2. 刪除一周內未被存取的 a.out 或 *.o 檔
find . \( -name a.out -o -name '*.o' \) -atime +7 -exec rm {} \;

# 3. 查找 /var/log 下 30 天前、大於 100M 的 .log 檔並壓縮
find /var/log -name '*.log' -mtime +30 -size +100M -exec gzip {} \;

進階技巧

  • 配合 xargs 處理大量檔案:find . -name '*.tmp' -print0 | xargs -0 rm -f(-print0/-0 安全處理含空格檔名)。
  • 輸出以 NUL 分隔:-print0 避免檔名含換行符導致錯誤。
  • 只列出目錄:find . -type d。
Copyright © Windows教程網 All Rights Reserved