如何打乱包含空格的文件名数组?

dea*_*sin 2 arrays string bash shuffle

我有一个文件名数组,其中可能包含空格。我正在使用该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
Run Code Online (Sandbox Code Playgroud)

输出:

file with spaces.txt

file

with

spaces.txt
Run Code Online (Sandbox Code Playgroud)

Sto*_*ica 5

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

mapfile -t vids < <(shuf -e "${vids[@]}")
Run Code Online (Sandbox Code Playgroud)

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

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