Home > Net >  Find all files matching pattern in directory and copy subdirectories and files found
Find all files matching pattern in directory and copy subdirectories and files found

Time:05-19

I have a directory structure of the following:

$DIRECTORY/*.xml
$DIRECTORY/*.others
$DIRECTORY/subdir1/*.xml
$DIRECTORY/subdir1/*.others
$DIRECTORY/subdir2/*.xml
$DIRECTORY/subdir2/*.others

And wish to copy all xml files into $OUTPUT_DIRECTORY including the directory structure of $DIRECTORY so the result will be:

$OUTPUT_DIRECTORY/*.xml
$OUTPUT_DIRECTORY/subdir1/*.xml
$OUTPUT_DIRECTORY/subdir2/*.xml

I know find has both -exec and -execdir which will use the output of find as the arguments to the command specified. I can't however see a way to specify "-execdir but keep subdirectories as the following arguments". Worth noting that the subdirectory can be however n deep.

Is there a way to do this purely with find, or will some other CLUs be needed?

find "${DIRECTORY}" -name '*.xml' -execdir cp "{}" "${OUTPUT_DIRECTORY}" \;

CodePudding user response:

You might want to use rsync instead of find:

rsync -amv --include='*/' --include='*.xml' --exclude='*' "$DIRECTORY"/ "$OUTPUT_DIRECTORY"
  • Related