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

后端 未结 3 1153
眼角桃花
眼角桃花 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;
    

提交回复
热议问题