简单的方法来洗牌在BASH外壳数组中的元素? [英] Simple method to shuffle the elements of an array in BASH shell?
问题描述
我可以做到这一点在PHP,但我想在bash shell中工作。我需要一个数组,然后随机洗牌的内容并转储到 somefile.txt
。
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
.
所以给定数组Heresmyarray,元素 A; B; C; d,E,F;
它会产生一个输出文件,输出。 TXT
,这将包含的元素 F;℃; b; A,E,D,
So given array Heresmyarray, of elements a;b;c;d;e;f;
it would produce an output file, output.txt
, which would contain elements f;c;b;a;e;d;
元素需要保留分号分隔符。我已经看到了一些的bash shell数组操作,但没有一种看上去甚至接近这个简单的概念。感谢您的任何帮助或建议!
The elements need to retain the semicolon delimiter. I've seen a number of bash shell array operations but nothing that seems even close to this simple concept. Thanks for any help or suggestions!
推荐答案
如果你只是想将它们放到一个文件(使用重定向>)
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;
如果你的数据有&放大器; #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;
这篇关于简单的方法来洗牌在BASH外壳数组中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!