如何打乱一组有空格的文件名



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

#!/bin/bash
vids=()
vids+=("file with spaces.txt")
for arr in "${vids[@]}"; do
echo -e "$arrn"
done
vids=( $(shuf -e "${vids[@]}") )    #shuffle contents of array
for arr in "${vids[@]}"; do
echo -e "$arrn"
done
exit 0

输出:

file with spaces.txt
file
with
spaces.txt

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

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 '%sn' "${shuffledvids[@]}"    # Another way to print array elements, one per line

最新更新