web-dev-qa-db-ja.com

7日より古いファイルを削除する

7日以上経過したすべてのファイルを削除するコマンドを以下に記述しますが、機能しません。

find /media/bkfolder/ -mtime +7 -name'*.gz' -exec rm {} \;

これらのファイルを削除するにはどうすればよいですか?

74
Malihe Pakyari

@Josが指摘したように、name'*.gz'の間のスペースを見逃しました。また、コマンドを高速化するために、-type fオプションを使用してf ilesのみでコマンドを実行します。

したがって、固定コマンドは次のようになります。

find /path/to/ -type f -mtime +7 -name '*.gz' -execdir rm -- '{}' \;

説明:

  • findf iles/d irectories/l inksなどを見つけるためのUNIXコマンド.
  • /path/to/:検索を開始するディレクトリ。
  • -type f:ファイルのみを検索します。
  • -name '*.gz'.gzで終わるファイルをリストします。
  • -mtime +7:変更日が7日より古いもののみを考慮します。
  • -execdir ... \;:見つかったそのような結果ごとに、...で次のコマンドを実行します。
  • rm -- '{}':ファイルを削除します。 {}部分は、検索結果が前の部分から置き換えられる場所です。 --は、コマンド終了パラメータが、hyphenで始まるファイルのエラーのプロンプトを回避することを意味します。

または、次を使用します。

find /path/to/ -type f -mtime +7 -name '*.gz' -print0 | xargs -r0 rm --

man find から:

-print0 
      True; print the full file name on the standard output, followed by a null character 
  (instead of the newline character that -print uses). This allows file names that contain
  newlines or other types of white space to be correctly interpreted by programs that process
  the find output. This option corresponds to the -0 option of xargs.

次のことになるため、これはもう少し効率的です。

rm file1 file2 file3 ...

とは対照的に:

rm file1; rm file2; rm file3; ...

-execメソッドのように。


代替およびfasterコマンドは、 + の代わりにexecの\;ターミネーターを使用します。

find /path/to/ -type f -mtime +7 -name '*.gz' -execdir rm -- '{}' +

このコマンドは、ファイルが見つかるたびにではなく、最後に1回だけrmを実行します。このコマンドは、現代のfindで次のように-deleteオプションを使用するのとほぼ同じ速度です。

find /path/to/ -type f -mtime +7 -name '*.gz' -delete
129
αғsнιη

Findでファイルを慎重に削除してください。 -lsを指定してコマンドを実行し、削除するものを確認します

find /media/bkfolder/ -mtime +7 -name '*.gz' -ls。次に、履歴からコマンドを取得し、-exec rm {} \;を追加します

Findコマンドが実行できる損害を制限します。 1つのディレクトリだけからファイルを削除したい場合、-maxdepth 1は、/media/bkfolder /をタイプミスした場合に、サブディレクトリを検索したり、システム全体を検索したりすることを防ぎます。

私が追加する他の制限は、-name 'wncw*.gz'などのより具体的な名前引数、時間より新しい-mtime -31の追加、および検索されたディレクトリの引用です。これらは、クリーンアップを自動化する場合に特に重要です。

find "/media/bkfolder/" -maxdepth 1 -type f -mtime +7 -mtime -31 -name 'wncw*.gz' -ls -exec rm {} \;

2
zeke