开发者

How to randomize a list and iterate through the randomized list (bash)

I have written a little bash script that reads commands (one per line), in a text file. At the moment, the script (shown below), is executing the commands in a sequential order (i.e. in the same order entered in the file).

I would like help to modify the script below, so that it reads the commands into an array, then randomizes that array (i.e. list) before iterating though the randomized list.

This is what I have so far:

while read -r -a array
do
   python make_move.py "${array[@]}"
done < game_commands.dat

I am running bash 4.1.5 on Ubuntu 10.0.4 LTS

开发者_如何转开发

[[Edit]]

I need to execute ALL of the commands in the list, with each command being executed ONLY ONCE.


You can shuffle the lines of a file using the shuf command.

Edit: Your code using shuf would look

while read -r -a array
do
    python make_move.py "${array[@]}"
done < <(shuf game_commands.dat)


If you need to execute something like this on a system where shuf is not available, (bash 4 only, easily adaptable for most modern shells):

unset max s i
readarray -t _cmd < game_commands.dat
while (( max < ${#_cmd[@]} )); do
  (( i = RANDOM % ${#_cmd[@]} ))
  [[ $s == *,$i,*  ]] || {
     python make_move.py "${_cmd[i]}"
         (( max++ ))
        }
  s+=,$i,
done


Try sort -R. That will shuffle the lines randomly. EDIT: But the same lines will always appear in blocks...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜