我有两个带有照片的目录,每次运行脚本时,我想操纵它们以输出文件的随机顺序。我将如何创建这样的列表?
d1=/home/Photos/*.jpg
d2=/mnt/JillsPC/home/Photos/*.jpg
# somehow make a combined list, files = d1 + d2
# somehow randomise the file order
# during execution of the for;do;done loop, no file should be repeated
for f in $files; do
echo $f # full path to each file
done
如果你不需要,我不会使用变量。如果将几个命令与管道或进程替换链接在一起会更自然。这样,一切都对数据流进行操作,而无需一次性将整个名称列表加载到内存中。
您可以使用shuf
随机排列输入行,并find
每行列出一个文件。或者,为了最大程度地安全,让我们使用\0
分隔符。最后,带有进程替换的while 循环将一行一行地读入一个变量中。
while IFS= read -d $'\0' -r file; do
echo "$file"
done < <(find /home/Photos/ /mnt/JillsPC/home/Photos/ -name '*.jpg' -print0 | shuf -z)
也就是说,如果你确实想使用一些变量,那么你应该使用数组。数组正确处理带有空格和其他特殊字符的文件名,而常规字符串变量将它们全部弄乱。
d1=(/home/Photos/*.jpg)
d2=(/mnt/JillsPC/home/Photos/*.jpg)
files=("${d1[@]}" "${d2[@]}")
按顺序迭代很容易:
for file in "${files[@]}"; do
echo "$file"
done
不过洗牌很棘手。shuf
仍然是最好的工具,但它在数据流上效果最好。我们可以使用我们需要printf
的尾随来打印每个文件名,\0
以使其shuf -z
满意。
d1=(/home/Photos/*.jpg)
d2=(/mnt/JillsPC/home/Photos/*.jpg)
files=("${d1[@]}" "${d2[@]}")
while IFS= read -d $'\0' -r file; do
echo "$file"
done < <(printf '%s\0' "${files[@]}" | shuf -z)
进一步阅读:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句