Recursive search and copy while keeping the directory structure intact.

I recently needed to write a script that would search for a certain pattern in a file name and then copy that file from one directory to another.  If you use the ‘find’ command with the standard parameters you will end up with all the files matching the pattern, being placed into a single folder.

 In this case I needed the find command to maintain the directory structure (and create the folders if necessary) once a file matching the pattern was found.

The key to making this happen was to use the ‘–parent’ flag with find.  Here is an example of the command I ended up using:

 find . -wholename "*search/pattern*" -exec cp -p --parent '{}' /new/folder/ ';'

Leave a Reply

Your email address will not be published. Required fields are marked *