0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

指定したディレクトリ以下で、-nameオプションを使用して「特定の名前のファイルまたはディレクトリ以外」のすべてを削除する方法

Posted at

指定した名前のファイル(ディレクトリ)以外を削除するコマンド

  • とあるディレクトリで、テスト用のファイルをぽこぽこ作ってしまい、hogeという必要なディレクトリ以外のすべてのファイルやディレクトリを一括削除したいな、という局面がありました。
  • 実行したことがないコマンドだったので、調べて以下コマンドで実施したら無事にできました。
$ find /path/to/directory -mindepth 1 -maxdepth 1 ! -name 'hoge' -exec rm -r {} +
  • ! -nameがポイントですね。

各オプションの説明

  • find: ファイルを検索するコマンド。
  • /path/to/directory: 検索するディレクトリのパスを指定。
  • -mindepth 1: 検索を開始する階層の深さを指定。ここでは、指定したディレクトリ直下から探索を開始するために1を指定。
  • -maxdepth 1: 探索する階層の深さを指定。ここでは、指定したディレクトリ直下のみを探索するために1を指定。
  • ! -name 'hoge': -nameオプションで指定した名前以外を探すために、!オプションで'hoge'という名前以外を指定。
  • -exec: -execオプションを使用すると、指定したコマンドを検索結果の各項目に対して実行できる。
  • rm -r: rmコマンドはファイルを削除するために使用される。-rオプションは、ファイルがディレクトリの場合に再帰的に削除することを指定。
  • {}: -execオプションで指定されたコマンドの引数として、検索された各ファイルまたはディレクトリのパスを指定。
  • +: -execオプションの最後に+を指定すると、検索結果全体に対して一度だけコマンドを実行。これにより、ファイルやディレクトリが多数ある場合でも、1つずつ削除する必要がなく、処理が高速化される。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?