Copy files modified after specific date using cp switches

cpfindtimestamps

When I execute the command find . -mtime -60 I get the list of files modified within the last 60 days.

So when I execute find . -mtime -60 -exec cp {} /tmp/1 \; I can copy these files to a new directory for processing

However if I want to preserve the timestamps, I am unable to copy just the files needed when I execute find . -mtime -60 -exec cp -LR --preserve=timestamps {} /tmp/2 \;

What ends up happening is that ALL files in the source directory are copied instead of just the files I need.

Any solution here?

Best Answer

What is happening here is that when you use the -R option to cp and supply a directory as an argument, it copies everything in that directory. Moreover, this will not preserve the directory structure as any files in lower directories will be copied directly to /tmp/2. This may be what you want (see X Tian's answer for how to do it this way), but beware if any files have the same name, one will overwrite the other at the detination.

To preserve the directory structure, you can use cpio:

find . -mtime -60 -print0 | cpio -0mdp /tmp/2

If the -0 (or equivalent) option is unavailable, you can do this, but be careful none of your file names contains a newline:

find . -mtime -2 | cpio -mdp /tmp/2

cpio should also support the -L option, although be careful with this as in some cases it can cause an infinite loop.

Related Question