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:空檔案/目錄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 安全處理含空格檔名)。-print0 避免檔名含換行符導致錯誤。find . -type d。