Linux: how to copy a file with a certain name pattern for which the exact place in the complex directory-structure is unknown

I want to copy all files with the name XYZ* into one folder. The problem is that the files are in different subfolders and that not even the depth of the folder structure is the same for all files. Luckily, at least each file has a unique name.

Of course, I thought about the cp command but I guess the depth of the folder structure needs to be the same for this to work.


If you want to avoid starting many separate processes (as using find ... -exec cp ... may do) using bash (and don't have zsh for its ** form) you can do a single cp as follows:

cp -p $(find path/to/src -name 'XYZ*') path/to/dest

The $(...) form is a posix version of back-tick-quoted process substitution. Following is an example.

find . -name 'd*a'
cp -p $(find . -name 'd*a') ../zeta
ls ../zeta

These commands produced the following output:

./.?/dx2a
./.?/dx4a
./.tdot1/dx1a
./.tdot2/dx2a
cp: will not overwrite just-created `../zeta/dx2a' with `./.tdot2/dx2a'
dx1a  dx2a  dx4a

You can use find for this:

$ find path/to/src -type f -name XYZ\* -exec cp -p {} path/todest/ \;

If you use zsh instead of bash then you can do it with the ** file glob pattern. This recursively matches all subfolders.

cp path/to/src/**/XYZ* path/to/dest