在 BASH shell 中打乱数组元素的简单方法? [英] Simple method to shuffle the elements of an array in BASH shell?

查看:123
本文介绍了在 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; 它将产生一个输出文件 output.txt,其中将包含元素 f;c;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 " " "
" | shuf | tr -d "
"
  d;a;e;f;b;c;

$ echo "a;b;c;d;e;f;" | sed -r 's/(.[^;]*;)/ 1 /g' | tr " " "
" | shuf | tr -d "
" > 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 " " "
" | 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 " " "
" | shuf | tr -d "
"
d;c;f;&#abcde;e;a;
$ echo "a;&#abcde;c;d;e;f;" | sed -r 's/(.[^;]*;)/ 1 /g' | tr " " "
" | shuf | tr -d "
"
&#abcde;f;a;c;d;e;

这篇关于在 BASH shell 中打乱数组元素的简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆