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

每天一個 Linux 指令(22):find 指令詳解

本文整理 find 指令常用參數的實例與使用時的注意事項。

一、-name 參數

1)在指定目錄及其子目錄中,查找與檔名相符的檔案:

[sunjimeng@localhost home]$ find ~ -name "less*" -print
/home/sunjimeng/Documents/less1
/home/sunjimeng/Documents/less2

其中 ~ 是一個代位符,代表個人目錄位址。由於每個使用者都有自己的個人目錄,用 ~ 統一替代這個因人而異卻有規可循的位址,能確保某些情況下的相容性。以 root 登入時 ~ 代表 /home/root,以 username 登入時則代表 /home/username。

補充:在 Linux 及 Unix 的 sh 中,以 $ 開頭的字串表示 shell 中定義的變數。$PATH 是系統的指令搜尋路徑,相當於 Windows 的 %path%;$HOME 則是使用者主目錄,也就是登入後的工作目錄,而波浪號 ~ 就代表你的 $HOME 目錄。

2)查找當前目錄下以大寫字母開頭、數字結尾的文件(注意 [] 的用法):

[sunjimeng@localhost Document]$ find . -name "[A-Z]*[1-9]"
./B.text3
./C.text6
[sunjimeng@localhost Document]$ find . -name "[A-Z]*"
./B.text3
./C.text6
./D.text

3)查找整個 Linux 檔案系統中的所有檔案(會讓系統高負荷運行):

[sunjimeng@localhost Document]$ find / -name "*"

由於 find 是透過背景遍歷整顆磁碟來搜尋,除了檔名還能比對權限、內容等,因此相當耗費資源。相較之下,which、whereis 等指令因為是透過資料庫的鍵值對應快速查找,效率高出許多。

二、-perm 參數

按檔案權限模式查找時,建議使用八進位的權限表示法。

1)按權限查找並分頁顯示:

[root@localhost home]# find . -perm 755 |more -5
.
./sunjimeng/.mozilla
./sunjimeng/.mozilla/extensions
--more--

find -perm 依權限查找有三種形式:

find -perm mode:嚴格匹配,檔案權限轉換成數字後必須與 mode 一模一樣,位數不足會自動補 0。

find -perm -mode:mode 換算成二進位後,所有為 1 的位都必須在檔案權限中被滿足,效果是匹配「權限比 mode 更充足」的檔案。

find -perm +mode:與 -mode 不同,+mode 只需其中任一個 1 的部分被匹配即可。

Linux 中檔案或目錄對所屬使用者 u、所屬組 g、其他 o 分別擁有讀 r、寫 w、執行 x 三種權限。將每部分的三個權限位看作二進位數,最大值為 7(2^3-1),代表可讀可寫可執行。

三、-prune 參數

若查找時想忽略某個已知沒有目標檔案的目錄,可用 -prune 指出要忽略的目錄。注意:若同時使用 -depth 選項,-prune 會被忽略。

1)查詢時忽略特定目錄:

[root@localhost sunjimeng]# find Document -path "Document/newDir" -prune -o -print
Document
Document/t1.txt
Document/t2.txt
Document/all.txt

2)find 後預設只能跟一個參數命令,若要執行其他命令需用 -o 連接。若不加上 -print,輸出的是要忽略的資料夾路徑;搭配 -exec 則可執行其他操作:

[root@localhost sunjimeng]# find Document -path "Document/newDir" -prune -o -exec ls -l {} \;

3)忽略多個資料夾,可用 \( ... \) 將多個 -path 組合起來:

[root@localhost Documents]# find . \( -path "./Dir" -o -path "./findDir" \) -prune -o -exec ls -l {} \;

注意 -path 必須帶 ./ 前綴才能匹配,只寫 "findDir" 是無效的。

四、-user 參數

1)查找屬於特定使用者的檔案與目錄:

[root@localhost Document]# find . -user sunjimeng -exec ls -l {} \;

2)查找不屬於任何使用者的檔案:

[root@localhost /]# find . -nouser -exec ls -l {} \;

此外還有許多用得到的參數,例如按大小 -size、按深度 -depth、按新舊 -newer、按更改或訪問時間 -mtime、按類型 -type 等,這裡不一一舉例。

Copyright © Linux教程網 All Rights Reserved