find 是 Linux 下最強大的檔案搜尋工具,支援按名稱、類型、大小、時間、權限等多維度條件遞歸查找,並可結合 -exec 或 xargs 執行後續操作。
find [路徑] [條件] [動作]
find . -print # 列出所有檔案/目錄(\n 分隔)
find . -print0 # \0 分隔,適合檔名含換行符的情況
find . -name "*.txt" # 大小寫敏感匹配
find . -iname "*.txt" # 忽略大小寫
# 或條件:.txt 或 .pdf
find . \( -name "*.txt" -o -name "*.pdf" \) -print
# 且條件:以 a 開頭且 .txt 結尾
find . \( -name "*.txt" -a -name "a*" \) -print
# 非條件(德摩根定律)
find . -not \( -name "*.txt" -a -name "a*" \) -print
find . ! -name "*.txt" -print
find /home/user -path "*sh" # 路徑整體匹配
find . -regex ".*\(\.py\|\.sh\)$" # 正則匹配路徑
find . -maxdepth 1 -type f # 只搜尋當前目錄
find . -mindepth 2 -type f # 至少兩層子目錄
find . -type f # 普通檔案
find . -type d # 目錄
find . -type l # 符號連結
# 其它:c(字符設備) b(塊設備) s(套接字) p(管道)
| 參數 | 含義 | 單位 |
|---|---|---|
| -atime | 訪問時間 | 天 |
| -mtime | 內容修改時間 | 天 |
| -ctime | inode 變更時間 | 天 |
| -amin/-mmin/-cmin | 同上 | 分鐘 |
find . -type f -atime -7 # 7 天內被訪問
find . -type f -atime +7 # 7 天前被訪問
find . -type f -newer file.txt # 比參考檔案新
find . -type f -size +2k # 大於 2KB
find . -type f -size -2k # 小於 2KB
# 單位:b(512B) c(Byte) k(MB) M(G) G
find . -type f -name "*.swp" -delete
find . -type f -perm 644 -print
find . -type f -user root -print
# 將所有 .c 檔合併
find . -type f -name "*.c" -exec cat {} \; > all.c
# 複製 10 天前的 .txt 到 /tmp
find . -type f -mtime +10 -name "*.txt" -exec cp {} /tmp \;
# 配合 xargs 處理大量檔案(需 -print0/-0 配對)
find . -type f -name "*.txt" -print0 | xargs -0 rm -f
find . \( -name ".git" -prune \) -o \( -type f -print \)
掌握 find 核心在於理解「條件邏輯」與「動作傳遞」,靈活組合可解決 90% 的檔案搜尋與批次處理需求。