将现有数组中的所有元素传递给xargs(Pass all elements in existing array to xargs)

编程入门 行业动态 更新时间:2024-10-26 15:26:24
将现有数组中的所有元素传递给xargs(Pass all elements in existing array to xargs)

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

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

编辑:找到作品

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

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

编辑2:

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

I am trying to pass an array of file paths to xargs to move them all to a new location. My script is currently working as follows:

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

Edit: Find works

I tried the following and it moved all the files. Is this the best way to do it? And is it moving the files one by one, so the terminal is not overloaded?

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

Edit 2:

For future reference, I tested the accepted answer method versus the method in my first edit using time(). After running both methods 4 times, my method had an average of 0.659s and the accepted answer was 0.667s. So neither method works any faster than the other.

最满意答案

当你这样做

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

When you do

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

xargs treats the entire line as a singe argument. You should split each element of the array to a new line, and then xargs should work as expected:

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

Or if your filenames can contain newlines, you can do

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

更多推荐

本文发布于:2023-08-05 01:25:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1426167.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   元素   xargs   Pass   existing

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!