Copy files based on date with structure of directories

Solution 1:

There is the --preserve=all option to cp; see man cp.

But I recommend to use rsync instead of cp; it's much more versatile, and it's easy to make it keep the timestamps, and to copy only newer files. It has some learning curve with all those options that it supports, but it's well worthwhile to dive into that.

The normal use case looks about like this:

rsync -n -av /some/where/sourcedir .

This recursively replicates sourcedir to the current directory as a subdirectory sourcedir/. It won't touch files that are already there and have the same timestamp / content. The -n option means it's just a dry run so you can see what it would do (together with -v for verbose). Once you are happy with what it would do, run it without -n:

rsync -av /some/where/sourcedir .

You can call that repeatedly; if it no longer does anything, it's well and truly finished.

You can also delete files that are no longer in the source directory tree with --delete:

rsync -av --delete /some/where/sourcedir .

If you append a trailing slash to the source path, it doesn't create a sourcedir/ subdirectory on the destination, but copies it directly into that subdirectory. Together with --delete, it creates a 1:1 copy of that tree in the current directory, also deleting everything that isn't in the source subtree:

rsync -av --delete /some/where/sourcedir/ .

Again, add -n to see what it would do. In general, I highly recommend to always use -n first to confirm that it will do what you want it to do.

There are tons of other options (like --exclude=); see man rsync.