copy files modified after specific date using cp switches

44,335

Solution 1

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.

Solution 2

You should exclude directories, the first file find prints is . in addition you use the recursive option on the copy.

So following is more what you intended, however as Graeme points out, cpio -pdm will preserve the original directory structure, cp will only copy into destination directory.

find . -mtime -60 -type f -exec cp -Lv --preserve=timestamps {} /tmp/2 \;

I'm leaving this answer to highlight the difference between Graeme and this solution. Since I do think it adds something to the overall answer to original question. Other readres might find this interesting.

Solution 3

This preserves timestamps across directories and files:

find . -mtime -60 -type f -exec cp --parents -fuav {} /tmp/2 \;

Tested using CentOS 7.2.

Share:
44,335

Related videos on Youtube

cyberjar09
Author by

cyberjar09

Updated on September 18, 2022

Comments

  • cyberjar09
    cyberjar09 almost 2 years

    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?

  • Graeme
    Graeme over 10 years
    You are better using + instead of \; as what you are doing will invoke one cp per file, this is not necessary. Also, this won't preserve the directory structure and may lead to some files overwriting each other if they have the same name.
  • X Tian
    X Tian over 10 years
    Great comment, You are absolutely correct on all 3 accounts. I'll update just to highlight the recursive, directory error.