使用xargs将目录从查找结果发送到另一个目录

时间:2012-12-16 08:32:06

标签: shell find xargs mv

我有以下命令:

find . -type d -mtime 0 -exec mv {} /path/to/target-dir \;

这会将创建的目录移动到另一个目录。如何使用xargs代替exec来执行相同的操作。

5 个答案:

答案 0 :(得分:39)

如果您有GNU mv(以及findxargs),则可以使用-t选项mv(和{{1} } -print0find -0}:

xargs

请注意,现代版find . -type d -mtime -0 -print0 | xargs -0 mv -t /path/to/target-dir (与POSIX 2008兼容)支持find代替+,其行为与;大致相同,而不使用xargs }:

xargs

这使得find . -type d -mtime -0 -exec mv -t /path/to/target-dir {} + 将方便的文件(目录)名称组分组到程序的单个调用中。您没有对find提供的mv传递的参数数量进行控制,但您实际上很少需要这样做。这仍然取决于GNU xargs的{​​{1}}选项。

答案 1 :(得分:38)

使用BSD xargs(对于 OS X 和FreeBSD),您可以使用为此构建的-J

find . -name some_pattern -print0 | xargs -0 -J % mv % target_location

这会将some_pattern中与. target_location匹配的任何内容移至-I

使用GNU xargs(对于 Linux 和Cygwin),请改为使用find . -name some_pattern -print0 | xargs -0 -I % mv % target_location

-i

GNU xargs的弃用-I{}选项隐含find . -name some_pattern -print0 | xargs -0 -i mv {} target_location ,可以按如下方式使用:

-I

请注意,BSD xargs也有一个{{1}}选项,但这样做会有所不同。

答案 2 :(得分:3)

find ./ -maxdepth 1 -name "some-dir" -type d -print0 | xargs -0r mv -t x/

<强>找到: 使用选项-print0,输出将以'\ 0'结尾;

<强> xargs的: 使用选项-0,它会将args拆分为'\ 0'但是空格,-r表示no-run-if-empty,因此如果find没有,则不会出现任何错误得到任何输出。 (-r是GNU扩展名。)

当我不确定目标文件是否存在时,我通常在脚本中使用它。

答案 3 :(得分:2)

find对此并不是一个好工具。我想你想将所有子目录移动到另一个目录中。 find会输出

之类的内容
./a
./a/b
./a/b/c
./a/b/c/d

首先移动./a后,您只会在所有子目录中收到“没有此类文件或目录”的错误。

你应该只使用mv */ /another/place - 通配符上的尾部斜杠将扩展限制为只有dirs。

答案 4 :(得分:0)

如果您不使用GNU mv,则可以使用该命令:

find . -depth -type d -mtime 0 -exec bash -c 'declare -a array;j=1;for i; do array[$j]="$i"; j=$((j+1));done; mv "${array[*]}" /path/to/target-dir' arg0 {} +

否则,这是一个更简单的解决方案,不需要xargs:

find . -depth -type d -mtime 0 -exec mv -t /path/to/target-dir {} +

请注意,我添加了-depth,否则当目录及其某个子目录都要处理时,你会遇到错误。