假设文件名没有空格,只需替换
List::Util::shuffle的输出即可.
原文链接:https://www.f2er.com/bash/386917.htmlfor i in `perl -MList::Util=shuffle -e'$,=$";print shuffle<*.txt>'`; do .... done
如果文件名确实有空格但没有嵌入的换行符或反斜杠,请一次读取一行.
perl -MList::Util=shuffle -le'$,=$\;print shuffle<*.txt>' | while read i; do .... done
要在Bash中完全安全,请使用以NUL结尾的字符串.
perl -MList::Util=shuffle -0 -le'$,=$\;print shuffle<*.txt>' | while read -r -d '' i; do .... done
效率不高,但如果需要,可以在纯Bash中执行此操作. sort -R在内部执行类似的操作.
declare -a a # create an integer-indexed associative array for i in *.txt; do j=$RANDOM # find an unused slot while [[ -n ${a[$j]} ]]; do j=$RANDOM done a[$j]=$i # fill that slot done for i in "${a[@]}"; do # iterate in index order (which is random) .... done
或者使用传统的Fisher-Yates shuffle.
a=(*.txt) for ((i=${#a[*]}; i>1; i--)); do j=$[RANDOM%i] tmp=${a[$j]} a[$j]=${a[$[i-1]]} a[$[i-1]]=$tmp done for i in "${a[@]}"; do .... done