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

橙三吉。 提交于 2020-01-04 07:26:21

问题


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.


回答1:


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)



回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/7742218/how-to-randomize-a-list-and-iterate-through-the-randomized-list-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!