如何在 Unix 命令行或 shell 脚本中打乱文本文件的行? [英] How can I shuffle the lines of a text file on the Unix command line or in a shell script?
问题描述
我想随机打乱文本文件的行并创建一个新文件.该文件可能有几千行.
I want to shuffle the lines of a text file randomly and create a new file. The file may have several thousands of lines.
我如何使用 cat
、awk
、cut
等来做到这一点?
How can I do that with cat
, awk
, cut
, etc?
推荐答案
您可以使用 换行
.至少在某些系统上(似乎不在 POSIX 中).
You can use shuf
. On some systems at least (doesn't appear to be in POSIX).
正如 jleedev 指出的:sort -R
也可能是一个选项.至少在某些系统上;好吧,你明白了.已经指出 sort -R
并没有真正洗牌,而是根据它们的哈希值对项目进行排序.
As jleedev pointed out: sort -R
might also be an option. On some systems at least; well, you get the picture. It has been pointed out that sort -R
doesn't really shuffle but instead sort items according to their hash value.
[编者注:sort -R
几乎 shuffle,除了重复行/排序键总是以结束紧挨着.换句话说:只有 unique 输入行/键才是真正的 shuffle.虽然输出顺序确实由哈希值决定,但随机性来自选择随机哈希函数 - 请参阅手册.]
这篇关于如何在 Unix 命令行或 shell 脚本中打乱文本文件的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!