2019年1月14日 星期一

Find 指令用法教學

筆記一下自己常用的 Find 指令


1. 找出 . 底下的 txt 檔

#
find . -name "*.txt"

2. 找出 . 底下非 txt 的附檔名的檔案

#
find . -not -name "*.txt"

3. 刪除 . 底下 txt 檔案,有兩種作法

#
# 系統詢問之後才刪除
# 先把 -exec 後面的東西先清掉, 用 -print 來先確認輸出 , 或將以刪除資訊寫進log
# rm 可以多用 -i 的參數來加以確認
find . -name "*.txt " -exec echo "Delete {}" \; -exec rm -i {} \;

#
#不用確認
find . -name "*.txt " -exec echo "Delete {}" \; -exec rm "{}" \;

#
# 系統直接刪除
find . -delete -name "*.txt "
find . -name "*.txt " | xargs /bin/rm -rf

4. 如何刪除 5 天前的資料呢?

#
find ${path_name} -type f -mtime +5 -exec rm "{}" \;
find ${path_name} -type f -mtime +5  | xargs /bin/rm -rf
find ${path_name} -delete -type f -mtime +5

5. 找出 5 天以內修改的資料

#
find . -type f -mtime -5 -name "*.txt"

6. find 後只顯示目錄名稱不顯示路徑

#
find . -maxdepth 1 -type d  -exec basename {} \;
find . -maxdepth 1 -type d | awk -F"/" '{print $NF}'
find . -maxdepth 1 -type d | sed 's!.*\/\([^\/]*\).*!\1!g'

7. find 後只顯示目錄名稱不顯示路徑,也不顯示第一個 . 目錄

#
find . -maxdepth 1 -mindepth 1 -type d -exec basename {} \;

8. 找尋所有檔案大小大於 50MB 的檔案

#
find ${path_name} -type f -size +50M

9. 找尋所有檔案大小小於 50MB 的檔案

#
find ${path_name} -type f -size -50M

10. 尋找超過 10 分鐘沒有被存取或修改過的檔案

#
find ${path_name} -type f -amin +10

11. 尋找曾經在 10 分鐘內被存取或修改過的檔案

#
find ${path_name} -type f -amin -10

12. 尋找檔案建立時間已超過 30 天的檔案

#
find ${path_name} -type f -ctime +30