如何随机播放其中包含空格的文件名数组?

How can I shuffle an array of filenames that have spaces in them?

我有一组文件名,其中可能包含空格。我正在使用 shuf 命令,但它使用文件名中的空格作为分隔符,并在随机播放时打断文件名。有没有办法解决这个问题,还是我必须放弃 shuf 命令?有什么建议吗?

#!/bin/bash

vids=()

vids+=("file with spaces.txt")

for arr in "${vids[@]}"; do
    echo -e "$arr\n"
done

vids=( $(shuf -e "${vids[@]}") )    #shuffle contents of array

for arr in "${vids[@]}"; do
    echo -e "$arr\n"
done

exit 0

输出:

file with spaces.txt

file

with

spaces.txt

您的方法不起作用的原因是 shell 将单词拆分应用于 $(...) 内命令的输出,并且无法将换行符视为分隔符。您可以使用 mapfile 将行读入数组(在 Bash 4+ 中):

mapfile -t vids < <(shuf -e "${vids[@]}")

或者在旧版本的 Bash 中,您可以使用老式的 while 循环:

vids2=()
while read -r item; do
    vids2+=("$item")
done < <(shuf -e "${vids[@]}")

@janos 已经解释了这个问题,所以我不会重复。但是还有另一种解决问题的方法:打乱数组索引(只是数字)而不是条目本身,然后按照打乱的顺序将元素复制到新数组中:

shuffledvids=()
for index in $(shuf -e "${!vids[@]}"); do    # The ! gets the indexes, rather than entries
    shuffledvids+=("${vids[index]}")
done
prinf '%s\n' "${shuffledvids[@]}"    # Another way to print array elements, one per line