简体   繁体   English

在 Linux 中根据修改日期复制文件

[英]Copying files based on modification date in Linux

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 ?如何使用-mtime复制文件?

Use the -exec option for find :find使用-exec选项:

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

-exec would copy every result returned by find to the specified directory ( targetdir in the above example). -exec会将find返回的每个结果复制到指定目录(上例中的targetdir )。

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 :)以上将2016年9月18日20:05:00之后创建的目录中的所有文件复制到FOLDER (今天前三个月:)

Be careful with the symbol for the find command.请注意 find 命令的符号。 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.如果您的文件名称中包含空格、换行符、制表符或通配符,您可以使用 Stéphane Chazelas 的任一解决方案。 The first is for GNU, and the second is for GNU or some BSDs :第一个用于 GNU,第二个用于 GNU 或某些BSD

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.注意: cat... 周围的引号是反引号,通常位于键盘的左上角。

You can then replace the echo command with a copy command:然后,您可以将echo命令替换为复制命令:

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

使用这个命令:

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

Example: select day 09/08/2017示例:选择日期 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

fileno表示当前要复制文件个数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM