An easy way to shuffle array elements in a BASH shell?

I can do this in PHP, but try to work in the BASH shell. I need to take an array and then randomly shuffle the contents and dump it to somefile.txt .

So, the given array Heresmyarray, from the elements a;b;c;d;e;f; , it will create an output file output.txt that will contain the elements f;c;b;a;e;d;

Elements must keep a comma separator. I have seen several operations with the BASH array, but nothing seems even close to this simple concept. Thanks for any help or suggestions!

+7
source share
3 answers

If you just want to put them in 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 elements into an 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; 
+8
source

From BashFaq

This function moves array elements in place using the Shuffle Knuth-Fisher-Yates 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[@]}" 

Exit

 $ ./shuff_ar > somefile.txt $ cat somefile.txt b;c;e;f;d;a; 
+7
source

The accepted answer is too inconsistent with the title of the question, although the details in the question are somewhat mixed. The question asks how to shuffle the elements of an array in BASH, and kurumi's answer shows how to manipulate the contents of the string.

kurumi nevertheless makes good use of the shuf command, and siegeX shows how to work with the array.

Putting the two together gives the real "easy way to shuffle the elements of the array in the BASH wrapper":

 $ myarray=( 'a;' 'b;' 'c;' 'd;' 'e;' 'f;' ) $ myarray=( $(shuf -e "${myarray[@]}") ) $ printf "%s" "${myarray[@]}" d;b;e;a;c;f; 
+6
source

All Articles