Simple method to shuffle the elements of an array in BASH shell?

后端 未结 3 1135
眼角桃花
眼角桃花 2020-11-29 09:37

I can do this in PHP but am trying to work within the BASH shell. I need to take an array and then randomly shuffle the contents and dump that to somefile.txt.

相关标签:
3条回答
  • 2020-11-29 10:03

    If you just want to put them into a file (use redirection > )

    $ echo "a;b;c;d;e;f;" | sed -r 's/(.[^;]*;)/ \1 /g' | tr " " "\n" | shuf | tr -d "\n"
      d;a;e;f;b;c;
    
    $ echo "a;b;c;d;e;f;" | sed -r 's/(.[^;]*;)/ \1 /g' | tr " " "\n" | shuf | tr -d "\n" > output.txt
    

    If you want to put the items in array

    $ array=( $(echo "a;b;c;d;e;f;" | sed -r 's/(.[^;]*;)/ \1 /g' | tr " " "\n" | shuf | tr -d " " ) )
    $ echo ${array[0]}
    e;
    $ echo ${array[1]}
    d;
    $ echo ${array[2]}
    a;
    

    If your data has &#abcde;

    $ echo "a;&#abcde;c;d;e;f;" | sed -r 's/(.[^;]*;)/ \1 /g' | tr " " "\n" | shuf | tr -d "\n"
    d;c;f;&#abcde;e;a;
    $ echo "a;&#abcde;c;d;e;f;" | sed -r 's/(.[^;]*;)/ \1 /g' | tr " " "\n" | shuf | tr -d "\n"
    &#abcde;f;a;c;d;e;
    
    0 讨论(0)
  • 2020-11-29 10:13

    From the BashFaq

    This function shuffles the elements of an array in-place using the Knuth-Fisher-Yates shuffle algorithm.

    #!/bin/bash
    
    shuffle() {
       local i tmp size max rand
    
       # $RANDOM % (i+1) is biased because of the limited range of $RANDOM
       # Compensate by using a range which is a multiple of the array size.
       size=${#array[*]}
       max=$(( 32768 / size * size ))
    
       for ((i=size-1; i>0; i--)); do
          while (( (rand=$RANDOM) >= max )); do :; done
          rand=$(( rand % (i+1) ))
          tmp=${array[i]} array[i]=${array[rand]} array[rand]=$tmp
       done
    }
    
    # Define the array named 'array'
    array=( 'a;' 'b;' 'c;' 'd;' 'e;' 'f;' )
    
    shuffle
    printf "%s" "${array[@]}"
    

    Output

    $ ./shuff_ar > somefile.txt
    $ cat somefile.txt
    b;c;e;f;d;a;
    
    0 讨论(0)
  • 2020-11-29 10:14

    The accepted answer doesn't match the headline question too well, though the details in the question are a bit ambiguous. The question asks about how to shuffle elements of an array in BASH, and kurumi's answer shows a way to manipulate the contents of a string.

    kurumi nonetheless makes good use of the 'shuf' command, while siegeX shows how to work with an array.

    Putting the two together yields an actual "simple method to shuffle the elements of an array in BASH shell":

    $ myarray=( 'a;' 'b;' 'c;' 'd;' 'e;' 'f;' )
    $ myarray=( $(shuf -e "${myarray[@]}") )
    $ printf "%s" "${myarray[@]}"
    d;b;e;a;c;f;
    
    0 讨论(0)
提交回复
热议问题