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?

指定したファイル以外を一括削除する方法

Last updated at Posted at 2025-04-07

ディレクトリ構造

project-root/
├── config/
│   ├── app.properties
│   ├── db.properties
│   ├── temp.txt
│   └── readme.md
├── resources/
│   ├── messages.properties
│   ├── dummy.json
│   ├── data.xml
│   └── nested/
│       ├── nested.properties
│       ├── notes.txt
│       └── info.log
└── scripts/
    ├── deploy.sh
    └── clean.properties

使用コマンド

上記から.propertiesがつくファイル以外をすべて削除したい場合

find ./project-root -type f ! name '*.properties' | xargs rm -f

xargs は前のコマンドの結果を次のコマンドの引数として渡してくれるコマンドなので、今回でいくとfindで探してきた`*.properties‘以外のものが引数として渡されて削除される形になります。

他には下記のような方法もあります。

find ./project-roo -type f ! -name '*.properties' -exec rm -f {} \;

-exec はfindで見つけたファイル1つ1つに対して別のコマンドを実行したいときに使用します。
ちなみにxargsはfindで見つけたファイルすべてに対して一括で実行してくれます。

追記

find ./project-roo -type f -name '*.properties' -exec rm -f {} \+

さいごを;ではなく+ にすることで1つ1つのファイルではなく、多くのファイルに対して(制限はある)実行できるそうです!

まとめ

どちらを使用してもいいとは思いますが、xargsを使用する方法でいくとファイル名にスペースなどが入っている場合に思った通りの動作にならない可能性もあるので使い分けるのがいいかと思われます。

0
0
2

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?