Copy a file to directories


TL;DR: copy source file to target directories given root path:

$ find <root> -type d -name <target> -exec cp <source> {} \;

Given the following directory structure:

$ tree
.
├── dir1
├── dir2
├── dir3
└── file

3 directories, 1 file

How can we copy file to dir1/, dir2/, and dir3/ to get something like this:

$ tree
.
├── dir1
│   └── file
├── dir2
│   └── file
├── dir3
│   └── file
└── file

3 directories, 4 files

cp

We can explicitly call cp to copy the source file to each target directory:

$ cp file dir1; cp file dir2; cp file dir3

But this doesn’t feel DRY—especially when the number of directories increases.

find

With find, we can list all the directories:

$ find . -type d
.
./dir2
./dir3
./dir1

To match the directory name starting with dir:

$ find . -type d -name 'dir*'
./dir2
./dir3
./dir1

Then we can execute cp and pass each directory as {}:

$ find . -type d -name 'dir*' -exec cp file {} \;


If you enjoyed this post, please consider supporting this site!