在 bash 中,查找、排序和复制

In bash, Find, Sort and Copy

我正在尝试 运行 搜索包含许多文件夹和文件的文件夹。我想找到最新的 20 个 quicktimes 并复制到特定目录“New_Directory”。

到目前为止我得到了这个:

find .  -type f -name '*.mov' -print0 | xargs -0 ls -dtl | head -20 | xargs -I{} echo {}

这会找到我的文件并使用 size/date/name 打印它们(以 ./ 开头)

但是如果我将命令更改为这个(在末尾添加 cp):

find .  -type f -name '*.mov' -print0 | xargs -0 ls -dtl | head -20 | xargs -I{} cp {} /Volume/New_Directory/

我收到错误:

cp: illegal option -- w
usage: cp [-R [-H | -L | -P]] [-fi | -n] [-apvXc] source_file target_file
cp [-R [-H | -L | -P]] [-fi | -n] [-apvXc] source_file ... target_directory
cp: illegal option -- w
usage: cp [-R [-H | -L | -P]] [-fi | -n] [-apvXc] source_file target_file
cp [-R [-H | -L | -P]] [-fi | -n] [-apvXc] source_file ... target_directory
.... (20 times)

我正在 mac OS.

上使用终端

请建议如何解决此问题或建议更好的方法。 谢谢。

尝试解构您的管道以查看发生了什么。

find .  -type f -name '*.mov' -print0 | xargs -0 ls -dtl | head -20 | 

为您提供 20 个最新 mov 文件的列表。丢失的看起来像:

-rw-r--r-- 1 ljm users 12449464 Jan 10 16:24 ./05ED-E769/DCIM/215___01/IMG_5902.mov
-rw-r--r-- 1 ljm users 14153909 Jan 10 16:00 ./05ED-E769/DCIM/215___01/IMG_5901.mov
-rw-r--r-- 1 ljm users 13819624 Jan 10 15:58 ./05ED-E769/DCIM/215___01/IMG_5900.mov

因此,您的 xargs|cp 会将此作为输入。

会是

cp -rw-r--r-- 1 ljm users 13819624 Jan 10 15:58 ./05ED-E769/DCIM/215___01/IMG_5900.mov /Volume/New_Directory/

如果我们查看您的错误消息,

cp: illegal option -- w

cp -r 可以,cp -rw 将产生此消息。所以这和我说的是一致的。

所以,问题是为什么在文案中-l。如果您删除长格式,您将得到您所需要的。

附带说明为什么 ls -d,如果您的 find 确保 -type f

find .  -type f -name '*.mov' -print0 | xargs -0 ls -t | head -20 | xargs -I{} cp {} /Volume/New_Directory/

应该做你想做的,但请记住你正在解析 ls 的输出,这被认为不是一个好主意。

就个人而言,我会

find . -type f -printf "%T@ %p\n" |
    sort -n |
    cut -d' ' -f 2- |
    tail -n 20 |
    xargs -I{} cp {} /Volume/New_Directory/

你使用下面的脚本。

find . -type f -name '*.mov' | ls -1t | head -n 20 |
xargs -n 1 -I {} realpath {} |
xargs -n 1 -I {} cp {} /Volume/New_Directory/