我正在尝试将一组文件路径传递给 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
>xargsxargs
,因为我希望有足够的文件来重载单个 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/