将现有数组中的所有元素传递给xargs

Mat*_*att 13 unix linux bash terminal xargs

我试图传递一个文件路径数组,xargs将它们全部移动到一个新的位置.我的脚本目前的工作方式如下:

FILES=( /path/to/files/*identifier* )
if [ -f ${FILES[0]} ]
  then
    mv ${FILES[@]} /path/to/destination
fi
Run Code Online (Sandbox Code Playgroud)

将FILES作为数组的原因是因为if [ -f /path/to/files/*identifier* ]如果通配符搜索返回多个文件,则失败.仅检查第一个文件,因为如果存在任何文件,将执行移动.

我想,以取代mv ${FILES[@]} /path/to/destination与传递线路${FILES[@]}xargs移动的每个文件.我需要使用,xargs因为我希望有足够的文件来重载单个mv.通过研究,我只能找到移动文件的方法,我已经知道哪些文件再次搜索文件.

#Method 1
ls /path/to/files/*identifier* | xargs -i mv '{}' /path/to/destination

#Method 2
find /path/to/files/*identifier* | xargs -i mv '{}' /path/to/destination
Run Code Online (Sandbox Code Playgroud)

有没有办法可以将现有数组中的所有元素传递${FILES[@]}xargs

以下是我尝试过的方法及其错误.

尝试1:

echo ${FILES[@]} | xargs -i mv '{}' /path/to/destination
Run Code Online (Sandbox Code Playgroud)

错误:

mv: cannot stat `/path/to/files/file1.zip /path/to/files/file2.zip /path/to/files/file3.zip /path/to/files/file4.zip': No such file or directory
Run Code Online (Sandbox Code Playgroud)

尝试2:我不确定是否xargs可以直接执行.

xargs -i mv ${FILES[@]} /path/to/destination
Run Code Online (Sandbox Code Playgroud)

错误:没有输出错误消息,但它在该行之后挂起,直到我手动停止它.

编辑:查找作品

我尝试了以下内容,它移动了所有文件.这是最好的方法吗?它是一个接一个地移动文件,所以终端没有超载?

find ${FILES[@]} | xargs -i mv '{}' /path/to/destination
Run Code Online (Sandbox Code Playgroud)

编辑2:

为了将来的参考,我测试了接受的答案方法与我在第一次编辑中使用的方法time().运行两种方法4次后,我的方法平均为0.659s,接受的答案为0.667s.所以这两种方法都不比另一种更快.

use*_*001 36

当你这样做

echo ${FILES[@]} | xargs -i mv '{}' /path/to/destination
Run Code Online (Sandbox Code Playgroud)

xargs将整行视为一个问题.您应该将数组的每个元素拆分为一个新行,然后xargs应该按预期工作:

printf "%s\n" "${FILES[@]}" | xargs -i mv '{}' /path/to/destination
Run Code Online (Sandbox Code Playgroud)

或者,如果您的文件名可以包含换行符,则可以执行此操作

printf "%s\0" "${FILES[@]}" | xargs -0 -i mv '{}' /path/to/destination
Run Code Online (Sandbox Code Playgroud)

  • @Roland:“mv”确实接受多个参数,但是使用您的命令传递一个*单个*参数(包括空格)。看起来“-i”和“-I”会导致设置“-L 1”,因此每次调用只能获取一项。但是,如果您查看此问题,则可以使用一些解决方法,例如:https://superuser.com/a/705651/301351 (2认同)