随机ARG为了for语句一个bash [英] Randomizing arg order for a bash for statement
问题描述
我有使用类似
对于我在* .TXT
做
OPS .....
做
for i in *.txt do ops..... done
有成千上万的文件,他们总是在因* .TXT扩张字母顺序进行处理。
There are thousands of files and they are always processed in alphanumerical order because of '*.txt' expansion.
有没有一种简单的方法来随机的顺序,仍然确保我处理所有的文件只有一次?
Is there a simple way to random the order and still insure that I process all of the files only once?
推荐答案
假设文件名没有空格,刚刚替补的列表::的Util ::洗牌。
Assuming the filenames do not have spaces, just substitute the output of List::Util::shuffle.
for i in `perl -MList::Util=shuffle -e'$,=$";print shuffle<*.txt>'`; do
....
done
如果文件名也有空间,但不具有嵌入式换行符或反斜线,一次读取一行。
If filenames do have spaces but don't have embedded newlines or backslashes, read a line at a time.
perl -MList::Util=shuffle -le'$,=$\;print shuffle<*.txt>' | while read i; do
....
done
要完全安全的猛砸,使用NUL结尾的字符串。
To be completely safe in Bash, use NUL-terminated strings.
perl -MList::Util=shuffle -0 -le'$,=$\;print shuffle<*.txt>' |
while read -r -d '' i; do
....
done
不是很有效的,但它是可能的,如果希望这样做在纯击。 排序-R
做这样的事情,在内部。
Not very efficient, but it is possible to do this in pure Bash if desired. sort -R
does something like this, internally.
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
还是使用传统的费雪耶茨洗牌。
Or use a traditional 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
这篇关于随机ARG为了for语句一个bash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!