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

时间:2018-12-12 06:15:32

标签: 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

输出:

file with spaces.txt

file

with

spaces.txt

2 个答案:

答案 0 :(得分:4)

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

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

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

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

答案 1 :(得分:4)

@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