Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Linux find 命令完整詳解:從入門到進階實戰

編輯:系統常見問題解答

find 是 Linux 下最強大的檔案搜尋工具,支援按名稱、類型、大小、時間、權限等多維度條件遞歸查找,並可結合 -exec 或 xargs 執行後續操作。

基本語法

find [路徑] [條件] [動作]

核心用法分類

1. 基礎列印與名稱匹配

find . -print                    # 列出所有檔案/目錄(\n 分隔)
find . -print0                   # \0 分隔,適合檔名含換行符的情況
find . -name "*.txt"             # 大小寫敏感匹配
find . -iname "*.txt"            # 忽略大小寫

2. 邏輯組合條件

# 或條件:.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

3. 路徑與正則匹配

find /home/user -path "*sh"      # 路徑整體匹配
find . -regex ".*\(\.py\|\.sh\)$" # 正則匹配路徑

4. 深度控制

find . -maxdepth 1 -type f       # 只搜尋當前目錄
find . -mindepth 2 -type f       # 至少兩層子目錄

5. 檔案類型搜尋

find . -type f   # 普通檔案
find . -type d   # 目錄
find . -type l   # 符號連結
# 其它:c(字符設備) b(塊設備) s(套接字) p(管道)

6. 時間戳篩選

參數含義單位
-atime訪問時間天
-mtime內容修改時間天
-ctimeinode 變更時間天
-amin/-mmin/-cmin同上分鐘
find . -type f -atime -7   # 7 天內被訪問
find . -type f -atime +7   # 7 天前被訪問
find . -type f -newer file.txt  # 比參考檔案新

7. 大小篩選

find . -type f -size +2k   # 大於 2KB
find . -type f -size -2k   # 小於 2KB
# 單位:b(512B) c(Byte) k(MB) M(G) G

8. 刪除匹配檔案

find . -type f -name "*.swp" -delete

9. 權限與擁有者

find . -type f -perm 644 -print
find . -type f -user root -print

10. 執行命令(-exec / xargs)

# 將所有 .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

11. 排除特定目錄

find . \( -name ".git" -prune \) -o \( -type f -print \)

掌握 find 核心在於理解「條件邏輯」與「動作傳遞」,靈活組合可解決 90% 的檔案搜尋與批次處理需求。

Copyright © Windows教程網 All Rights Reserved