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

标签 linux bash unix terminal xargs

我正在尝试将一组文件路径传递给 xargs 以将它们全部移动到新位置。我的脚本目前工作如下:

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

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

我想用将 ${FILES[@]} 传递给 的行替换 mv ${FILES[@]}/path/to/destination >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

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

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

尝试 1:

echo ${FILES[@]} | xargs -i mv '{}' /path/to/destination

错误:

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

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

xargs -i mv ${FILES[@]} /path/to/destination

错误: 没有输出错误消息,但它一直卡在该行之后,直到我手动将其停止。

编辑:查找作品

我尝试了以下操作,它移动了所有文件。这是最好的方法吗?是不是一个一个地移动文件,所以终端不会重载?

find ${FILES[@]} | xargs -i mv '{}' /path/to/destination

编辑2:

为了将来引用,我使用 time() 测试了接受的答案方法与我第一次编辑时的方法。运行这两种方法 4 次后,我的方法平均为 0.659 秒,接受的答案为 0.667 秒。因此,这两种方法都不比另一种更快。

最佳答案

当你做的时候

echo ${FILES[@]} | xargs -I {} mv '{}' /path/to/destination

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

printf "%s\n" "${FILES[@]}" | xargs -I {} mv '{}' /path/to/destination

或者如果你的文件名可以包含换行符,你可以这样做

printf "%s\0" "${FILES[@]}" | xargs -0 -I {} mv '{}' /path/to/destination

关于linux - 将现有数组中的所有元素传递给 xargs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19453618/

相关文章:

php - Magento Cron 作业/bin/bash : php7: command not found

python - 如果我将文件描述符限制设置为很大的数字,会有什么缺点?

linux - Dockerfile 在全局安装 Meteor,而不是本地安装

bash - 了解 bash 脚本开头的 PATH 变量导出

Bash =~ 在 OS X cmd 提示符下丢失 BASH_REMATCH 内容

bash - 从日期函数 fg : no job control 计算天数

.W 文件中的 C 源代码

ruby - 如何在 Ruby 中使用 Open#popen3 读取无缓冲的标准输出

linux - 如何将文本消息打印到控制台

linux - 引用包含引号并在 Bash 中作为变量给出的文件名