在 linux 中有一個 find 指令,可以幫助我們根據名稱、大小及時間等資訊快速的找到檔案與資料夾

另外,更好用的地方是可以搜尋檔案內容。

以下我們將介紹這個指令常用的地方,因為太過強大,所以比較少用的案例及詳細的參數就不寫上來囉!


這邊先介紹一下 -type [搜尋類型] 這個參數

b    block special file (特殊設備檔案)
c    character special file (特殊設備檔案)
d    directory (資料夾)
f     regular file (一般檔案)
l     symbolic link (連結檔)
p    FIFO (命令管道)
s    socket

  • 根據名稱搜尋特定檔案或資料夾, -name [檔案或資料夾名稱] 或不區分大小寫 -iname [檔案或資料夾名稱]
    find [path] [expression]
    // 尋找家目錄底下的 test.txt 資料夾或檔案
    find ~ -name "test.txt"
    // 尋找家目錄底下的 test 資料夾或檔案
    find ~ -name "test"
    // 尋找家目錄底下的 test 檔案
    find ~ -name "test" -type f
    // 尋找家目錄底下前綴為 tes 的檔案 (* 代表任意長度的字串)
    find ~ -name "tes*" -type f
    // 尋找家目錄底下名稱包含 test(不分大小寫) 的資料夾
    find ~ -iname "*test*" -type d
    
  • 根據大小及時間搜尋特定檔案或資料夾, -size [ckMGTP]    -atime [time]     -amin [min]
    find [path] [expression]
    // 尋找家目錄底下大於 2M 的檔案
    find ~ -size +2M -type f
    // 尋找家目錄底下小於 100k 的資料夾
    find ~ -size -100k -type d
    // 尋找家目錄底下超過7天沒被修改或存取的 test 檔案
    find ~ -name "test" -type f -atime +7
    // 尋找家目錄底下40分鐘內有修改或存取過的檔案
    find ~ -amin -40 -type f
    // 尋找家目錄底下名稱包含 test 的資料夾並且擁有者為 test
    find ~ -name "*test*" -type d -user test
    
  • 檔案內容全文搜尋, -exec [program](將搜尋到的檔名交給program), grep -H(將符合的檔案路徑列出),{} (將被取代為檔案名稱路徑),\ (代表 exec 的參數結束)
    find [path] [expression]
    // 尋找家目錄底下的 php 檔,並且內容包含test字串
    find ~ -name "*.php" -exec grep -H "test" {} \;
    

 

參考資料:

http://blog.miniasp.com/post/2010/08/27/Linux-find-command-tips-and-notice.aspx

https://help.ubuntu.com/community/find

http://falldog7.blogspot.tw/2008/01/linux.html

Leave a Reply