Find and Copy Files While Preserving the Folder Structure in Linux

In Linux in order to find files following a pattern we use the “find” command:

find [parent folder] -name “[regular expression]”

In order to copy files found by this command we can pipe the output into the “xargs” command (source):

find [parent folder] -name “[regular expression]” | xargs cp -t [destination folder]

The “cp” command comes with a “–parents” switch where, if used, it would create the same folder structure in the target location:

cp [file(s) or folder(s)] [destination folder] –parents

By combining these features we can now use “find“, “xargs“, and “cp” commands together to have the files of interest be copied into a destination folder while preserving the folder structure:

find [parent folder] -name “[regular expression]” | xargs cp -t [destination folder] –parents

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: