[英]How to copy the top 10 most recent files from one directory to another?
Al my html files reside here : 我的html文件驻留在这里:
/home/thinkcode/myfiles/html/
I want to move the newest 10 files to /home/thinkcode/Test
我想将最新的10个文件移动到
/home/thinkcode/Test
I have this so far. 到目前为止我有这个。 Please correct me.
请指正。 I am looking for a one-liner!
我正在寻找一个单行!
ls -lt *.htm | head -10 | awk '{print "cp "$1" "..\Test\$1}' | sh
ls -lt *.htm | head -10 | awk '{print "cp " $9 " ../Test/"$9}' | sh
Here is a version which doesn't use ls
. 这是一个不使用
ls
的版本。 It should be less vulnerable to strange characters in file names: 它应该不易受文件名中的奇怪字符的影响:
find . -maxdepth 1 -type f -name '*.html' -print0
\| xargs -0 stat --printf "%Y\t%n\n"
\| sort -n
\| tail -n 10
\| cut -f 2
\| xargs cp -t ../Test/
I used find
for a couple of reasons: 我使用
find
有几个原因:
1) if there are too many files in a directory, bash will balk at the wildcard expansion*. 1)如果目录中的文件太多,bash将会忽略通配符扩展*。
2) Using the -print0
argument to find
gets around the problem of bash expanding whitespace in a filename in to multiple tokens. 2)使用
-print0
参数来find
bash将文件名中的空格扩展为多个标记的问题。
* Actually, bash shares a memory buffer for its wildcard expansion and its environment variables, so it's not strictly a function of the number of file names, but rather the total length of the file names and environment variables. *实际上,bash为其通配符扩展及其环境变量共享内存缓冲区,因此它不是文件名数量的函数,而是文件名和环境变量的总长度。 Too many environment variables => no wildcard expansion.
环境变量太多=>没有通配符扩展。
EDIT: Incorporated some of @glennjackman's improvements. 编辑:纳入@ glennjackman的一些改进。 Kept the initial use of
find
to avoid the use of the wildcard expansion which might fail in a large directory. 保持最初使用
find
以避免使用可能在大目录中失败的通配符扩展。
ls -lt *.html | head -10 | awk '{print $NF}' | xargs -i cp {} DestDir
In the above example DestDir
is the destination directory for the copy. 在上面的示例中,
DestDir
是副本的目标目录。
Add -t
after xargs to see the commands as they execute. 在xargs之后添加
-t
以在执行时查看命令。 Ie, xargs -i -t cp {} DestDir
. 即,
xargs -i -t cp {} DestDir
。
For more information check out the xargs command . 有关更多信息,请查看xargs命令 。
EDIT : As pointed out by @DennisWilliamson (and also checking the current man page) re the -i
option This option is deprecated; use -I instead.
编辑 :正如@DennisWilliamson所指出的(并且还检查当前的手册页)重新使用
-i
选项This option is deprecated; use -I instead.
This option is deprecated; use -I instead.
. 。
Also, both solutions presented depend on the filenames in questions don't contain any blanks or tabs. 此外,所提供的两种解决方案都取决于问题中的文件名不包含任何空格或制表符。
cp
seems to understand back-ticked commands. cp
似乎理解反向命令。 So you could use a command like this one to copy the 10 latest files to another folder like eg /test
: 所以你可以使用像这样的命令将10个最新文件复制到另一个文件夹,例如
/test
:
cp `ls -t *.htm | head -10` /test
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.