PR

Linux 特定の更新日付以前のファイルを一括削除する方法

スポンサーリンク
Linux

ログ等が大量に存在しており、過去の不要なファイルを一括で削除する際、findコマンドのみで一括削除することが可能です。

一括削除コマンド

○日間更新がないファイルを削除するには、以下のfindコマンド+オプションを実行します。

find <削除対象検索ディレクトリ> -mtime <削除対象のファイル更新日> -type f -delete

使用例

対象ファイル

以下の更新日付のファイルが存在しています。

[root@cent76 ]# ls -l
total 0
-rw-r--r--  1 root root 0 Jan  1 01:00 20200101.txt
-rw-r--r--  1 root root 0 Jan  2 01:00 20200102.txt
-rw-r--r--  1 root root 0 Jan  3 01:00 20200103.txt
-rw-r--r--  1 root root 0 Jan  4 01:00 20200104.txt
-rw-r--r--  1 root root 0 Jan  5 01:00 20200105.txt
-rw-r--r--  1 root root 0 Jan  6 01:00 20200106.txt
-rw-r--r--  1 root root 0 Jan  7 01:00 20200107.txt
-rw-r--r--  1 root root 0 Jan  8 01:00 20200108.txt
-rw-r--r--  1 root root 0 Jan 10 01:00 20200110.txt

現時刻で -delete オプションを付与せずにfindコマンドで対象をリストします

[root@cent76 ]# date
Mon Jan 20 01:00:00 JST 2020
[root@cent76 tmp]# find ./ -mtime +14 -type f
./20200101.txt
./20200102.txt
./20200103.txt
./20200104.txt
./20200105.txt

14日間以上更新のなかったファイルを削除してみます

[root@cent76 ]# find ./ -mtime +14 -type f -delete
[root@cent76 tmp]# ls -l
total 0
-rw-r--r--  1 root root 0 Jan  6 01:00 20200106.txt
-rw-r--r--  1 root root 0 Jan  7 01:00 20200107.txt
-rw-r--r--  1 root root 0 Jan  8 01:00 20200108.txt
-rw-r--r--  1 root root 0 Jan 10 01:00 20200110.txt