Question

I want to copy the last three months' files from one directory to another directory, but I could find only listing the files by using the following command.

find . -mtime -90 -ls

How can I copy the files by using -mtime?

Was it helpful?

Solution

Use the -exec option for find:

find . -mtime -90 -exec cp {} targetdir \;

-exec would copy every result returned by find to the specified directory (targetdir in the above example).

OTHER TIPS

One can also select the exact date and time other than going back to a certain number of days:

cp  `find . -type f -newermt '18 sep 2016 20:05:00'` FOLDER

The above copies all the files in the directory that were created after 18 September 2016 20:05:00 to the FOLDER (three months before today :)

Be careful with the symbol for the find command. It is not this one: '

It is this, a backtick: `

Date selection is with this: '

If you have files with spaces, newlines, tabs, or wildcards in their names, you can use either of the solutions from Stéphane Chazelas. The first is for GNU, and the second is for GNU or some BSDs:

find . -type f -newermt '18 sep 2016 20:05:00' -exec cp -t FOLDER {} +
find . -type f -newermt '18 sep 2016 20:05:00' -exec sh -c 'cp "$@" FOLDER' sh {} +

I would first store the list of files temporarily and use a loop.

find . -mtime -90 -ls >/tmp/copy.todo.txt

You can read the list, if it is not too big, with

for f in `cat /tmp/copy.todo.txt`;
do echo $f;
done

Note: the quotes around cat... are backticks, often in the upper left corner of the keyboard.

You can then replace the echo command with a copy command:

for f in `cat /tmp/copy.todo.txt`;
do cp $f /some/directory/
done

Use this command:

for i in `ls -lrt | grep "jul" | awk '{print $9}' `; do cp $i* /some/folder/; done

Example: select day 09/08/2017

ls -l
 -rw-rw-rw-    1    root     system          943   Aug   09   02:59  File

for j in `ls -l |awk '{ if ($7 == "09") print $9}'`
    do
        mv $j $Destination;
    done
cp $(ls -t1 | head -n -(fileno))) dest

The fileno represents the number of the current files to be copied

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top