TL;DR: copy file
$SOURCEto directories$TARGETgiven path$ROOT:find $ROOT -type d -name $TARGET -exec cp $SOURCE {} \;
Problem
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 the following?
tree
.
├── dir1
│ └── file
├── dir2
│ └── file
├── dir3
│ └── file
└── file
3 directories, 4 files
Solution
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 {} \;