LoginSignup
40
35

More than 5 years have passed since last update.

複数のディレクトリにコピー、複数のディレクトリからコピー

Posted at

複数のディレクトリにコピー

findコマンドを使って、ファイルを複数のディレクトリにコピーする方法

here
 ├ dest1/
 ├ dest2/
 ├ dest3/
 ├ dest4/
 ├ dest5/
 └ src.txt

このようなディレクトリ構成でsrc.txtをdist1〜5までコピーしたいときは
findでコピー先のリストを作り、-execオプションでコマンドを指定する。

find . -name "dest*" -type d -exec cp src.txt {} \;

複数のディレクトリからコピー

here
 ├ src1/
   └ src1.txt
 ├ src2/
   └ src2.txt
 ├ src3/
   └ src3.txt
 ├ src4/
   └ src4.txt
 ├ src5/
   └ src5.txt
 └ dest/

逆のパターンも同じようにできます。

find . -name "src*" -type f -exec cp {} dest \;

複数のディレクトリからコピーするときは並列処理できるxargsが使えるので、こちらの方が便利かもしれない。
移動元のパスにスペースが入っているとおかしなことになるので -print0でfindのデリミタをnull文字に置き換える。

find . -name "src*" -type f -print0 | xargs -0 -J% cp % dest

複数のディレクトリを一箇所にコピー

各コピー元ディレクトリの中に同名のファイルがあると上書きコピーされるので
ディレクトリごとコピーしたい場合はこちら。

find . -name "src*" -type d -print0 | xargs -0 -J% cp -R % dest
40
35
1

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
40
35