find 是 Linux 與 UNIX 環境中最常被拿來找檔案的工具。它的運作方式很直覺:從你指定的起點出發,沿著目錄層級一層一層往下遞迴,把符合條件的檔案逐一挑出,接著再依需要執行後續動作。真正需要花時間學的其實不是指令本身,而是那些能大幅縮短搜尋範圍的參數。
-name 後面接的是檔名必須符合的字串,並可搭配萬用字元。例如 *.txt 代表所有以 .txt 結尾的檔案。
[root@localhost test]# touch {data,log,file,File,LOG}_{1,2,3,4,5,6}_{.txt,.pdf,.log,.conf}
[root@localhost test]# find . -name "*.txt" -print
若只要符合多個條件中的任一項,用 -o 串接即可;加上括號能避免運算順序造成誤解。
[root@localhost test]# find . \( -name "*.txt" -o -name "*.log" \)
另外,-iname 會忽略英文大小寫,-path 則是拿整段路徑來比對,同樣支援萬用字元。
「!」代表否定,下面的寫法會列出所有「不是」.txt 結尾的檔案。
[root@localhost test]# find . ! -name "*.txt" -print
find 預設會把所有子目錄都翻過一遍,在龐大的目錄樹裡這很浪費時間。-maxdepth 指定最大深度,-mindepth 指定最小深度,兩者必須緊跟在路徑之後。
[root@localhost ~]# find . -maxdepth 1 -type f
上面這行只會列出當前目錄下的普通檔案,不會往下鑽。
find . -type d -print
常見的類型參數如下:
普通檔案 f、目錄 d、符號連結 l、字元裝置 c、區塊裝置 b、Socket s、FIFO(命名管線)p。
Linux 每個檔案都帶有三種時間:存取時間(-atime,最近一次被讀取)、修改時間(-mtime,內容最後一次變動)、狀態變更時間(-ctime,權限或擁有者等中繼資料最後一次變動)。單位是天,+ 代表大於、- 代表小於,不加符號則是剛好等於。
[root@localhost ~]# find . -type f -atime 7 # 正好 7 天前被存取的檔案 [root@localhost ~]# find . -type f -mtime +7 # 修改時間超過 7 天的檔案 [root@localhost ~]# find . -type f -ctime -7 # 狀態變更在 7 天內的檔案
如果想要更精細,-amin、-mmin、-cmin 以「分鐘」為單位。而 -newer 是另一個好用的參數,它會拿一個檔案當基準,找出比它更新的所有檔案。
find . -type f -newer file.txt
可用的單位包含 b(512 位元組的區塊)、c(位元組)、w(字,2 位元組)、k(KB)、M(MB)、G(GB)。
[root@localhost tmp]# find . -type f -size 2k # 恰好 2k [root@localhost tmp]# find . -type f -size +2k # 大於 2k [root@localhost tmp]# find . -type f -size -2k # 小於 2k
-delete 會把搜尋結果直接刪掉,屬於不可逆操作,執行前請務必確認條件是否精準。
[root@localhost tmp]# find . -type f -name "*.swp" -delete
[root@localhost tmp]# find . -type f -perm 644 # 權限為 644 的檔案 [root@localhost tmp]# find . -type f -user reed # 擁有者為 reed 的檔案
-exec 讓 find 能把結果交給別的程式處理。{} 是特殊佔位字串,會被替換成每一個比對到的檔名,指令結尾必須以 \; 收尾。
[root@localhost tmp]# find . -type f -user reed -exec chown cathy {} \;
[root@localhost test]# find . -type f -mtime +10 -name "*.log" -exec cp {} /data/bk_log \;
[root@localhost test]# find /tmp/test/ -type f -name "*.txt" -exec printf "Text file: %s\n" {} \;
搭配 -prune 可以讓 find 略過某個子目錄,不必再逐一排除裡面的檔案。
[root@localhost test]# find . \( -name "jump_dir" -prune \) -o \( -type f -print \)
把這十個技巧串起來,日常九成的檔案查找需求都能用一行指令解決;真正需要小心的是 -delete 與 -exec 這類會改動系統的參數,下指令前先確認路徑與條件。