Linux Find 指令用法教學

筆記一下自己常用的 find 指令,適用於 FreeBSD 或者是 Linux 各大 distribution,系統管理這個指令就相當重要了,在搭配 grep,sed,awk,perl 可以快速找到自己要的檔案。我自己本身很常用到 grep,find,awk 這些撰寫 shell script。 底下先來介紹一下 find: 1. 找出 . 底下的 php 檔案

1
find . -name "*.php"

找出 . 底下非 php 副檔名檔案

1
find . -not -name "*.php"

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

1
2
3
4
5
6
7
8
9
#
# 系統詢問之後才刪除
# 先把 -exec 後面的東西先清掉, 用 -print 來先確認輸出
# rm 可以多用 -i 的參數來加以確認
find . -name "*.php" -exec rm -i {} \;
#
# 系統直接刪除
find . -delete -name "*.php"
find . -name "*.php" | xargs /bin/rm -rf

如何刪除 7 天前之料呢?

1
2
3
find /path_name -type f -mtime +7 -exec rm '{}' \;
find /path_name -type f -mtime +7  | xargs /bin/rm -rf
find /path_name -delete -type f -mtime +7

找出7天以內修改的資料

1
find . -type f -mtime -7 -name "*.php"

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

1
2
3
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'

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

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

-mmin (minutes) or -mtime (24 hour periods, starting from now) For example:

1
2
3
4
5
6
7
8
9
find . -mtime 0   # find files modified between now and 1 day ago
                  # (i.e., within the past 24 hours)
find . -mtime -1  # find files modified less than 1 day ago
                  # (i.e., within the past 24 hours, as before)
find . -mtime 1   # find files modified between 24 and 48 hours ago
find . -mtime +1  # find files modified more than 48 hours ago

find . -mmin +5 -mmin -10 # find files modifed between
                          # 6 and 9 minutes ago

See also