Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

find 指令用法詳解筆記

find 功能強大、選項繁多,是 Linux 下最實用的指令之一,缺點是搜尋速度較慢;若只求快速定位檔案,locate 會是更好的選擇。

一、基本語法

find pathname -option [-print] [-exec -ok command] {} \;

參數說明:

pathname:搜尋的起點目錄,相對路徑與絕對路徑皆可。
-print:把符合的結果輸出到標準輸出(預設行為)。
-exec command {} \;:對每個符合的檔案執行指定指令,注意「{}」與「\」之間必須有空格。
-ok command {} \;:與 -exec 相同,但執行前會逐一詢問確認。

二、常用選項

名稱:-name filename 依檔名搜尋。

檔案屬性:-perm xxxx 依權限搜尋;-user 依屬主;-group 依屬組;-nouser 找無效屬主(不在 /etc/passwd 中);-nogroup 找無效屬組。

時間屬性:-mtime -n +n 依修改時間(-n 為 n 天內,+n 為 n 天前);-atime 依存取時間;-ctime 依狀態變更時間;-newer file1 ! file2 找比 file1 新但比 file2 舊的檔案。

類型屬性:-type 搭配 b(區塊裝置)、d(目錄)、c(字元裝置)、p(管道)、l(符號連結)、f(一般檔案)。

其他:-size n [c] 依大小(加 c 表示以位元組計);-depth 先搜當前目錄再進子目錄;-fstype 限定檔案系統類型(可對照 /etc/fstab);-mount 不跨越掛載點;-follow 遇到符號連結時追蹤到目標檔案;-cpio 用 cpio 備份符合的檔案;-prune 忽略指定目錄。

另外這幾組的性差別值得留意:-amin/-atime 為「存取」時間的分钟/天單位,-cmin/-ctime 為「狀態變更」,-mmin/-mtime 為「內容修改」。

三、實例

(1)-name:可用比對符號或正則表達式。具體檔名可加引號也可不加,但使用比對模式時一定要加引號。

# find / -name "test.txt" -print
# find . -name "*.log" -print
# find / -name "[A-Z]*" -print          # 大寫字母開頭
# find / -name "[a-z]*[0-9]" -print     # 小寫字母開頭、數字結尾

(2)檔案屬性

# find / -perm 755 -print
# find / -user root -group root -print
# find . -nouser -nogroup -print        # 屬主與屬組都已被刪除

(3)時間屬性

$ find / -atime -2      # 最後 48 小時內存取過
$ find / -mtime -1      # 最後 24 小時內修改過

(4)忽略目錄

使用 -prune,注意不要與 -depth 同時使用,否則 -prune 會失效。

# find test -path "test/hello" -prune -o -print

原理:find [path...] [expression],-a 與 -o 是 shell 的短路求值,類似 && 與 ||。若 -path "test/hello" 為真,則求值 -prune 為真,因 -a 短路而跳過 -print;否則才執行 -print(利用 -o 的短路特性)。等價邏輯如下:

if -path "test/hello" then -prune else -print

忽略多個目錄:

find test \( -path test/test4 -o -path test/test3 \) -prune -o -print

若要同時限定檔名,把 -name 放在 -o 之後:

find test \( -path test/test4 -o -path test/test3 \) -prune -o -name "*.log" -print

(5)組合 -exec

# 查看當前目錄所有一般檔案的詳細資訊
$ find . -type f -exec ls -l {} \;

# 刪除五日以前修改過的檔案(運維常用於清理日誌)
$ find logs -type f -mtime +5 -exec -ok rm -rf {} \;

另一個實用好用的場景是「find 找檔、grep 找內容」:

# 在 /tmp 中找 *.h 並搜尋 TEST 字串
$ find /tmp -name "*.h" -exec grep "TEST" {} \; -print
$ find /tmp -name *.h | xargs -n50 grep TEST

# 把找到的檔案複製到指定位置
$ find /tmp -name test -exec cp '{}' /test ';'

特殊檔案則可用 cpio:

$ find dir -name filename -print | cpio -pdv newdir

find 的結果也能直接接管道處理,例如列出某個時間點修改過的檔案:

$ find ./ -name "*.php" | ls -l -full-time 2>/dev/null | grep "2016-07-03 22:39"

參考連結:每天一個 Linux 命令 find、Linux find 用法實例。

Copyright © Linux教程網 All Rights Reserved