我想随机洗牌文本文件的行,并创建一个新文件。该文件可能有几千行。
我如何用cat, awk, cut等做到这一点?
我想随机洗牌文本文件的行,并创建一个新文件。该文件可能有几千行。
我如何用cat, awk, cut等做到这一点?
当前回答
我们有一整套方案来完成这项工作:
sudo apt-get install randomize-lines
例子:
创建一个有序的数字列表,并保存到1000.txt:
seq 1000 > 1000.txt
要洗牌,只需使用
rl 1000.txt
其他回答
这是一个python脚本,我在我的主文件夹中保存为rand.py:
#!/bin/python
import sys
import random
if __name__ == '__main__':
with open(sys.argv[1], 'r') as f:
flist = f.readlines()
random.shuffle(flist)
for line in flist:
print line.strip()
在Mac OSX上,排序-R和shuf是不可用的,所以你可以在bash_profile中使用别名:
alias shuf='python rand.py'
在windows下,您可以尝试此批处理文件来帮助您洗牌data.txt,批处理代码的用法是
C:\> type list.txt | shuffle.bat > maclist_temp.txt
发出这个命令后,maclist_temp.txt将包含一个随机的行列表。
希望这能有所帮助。
一种简单而直观的方法是使用shuf。
例子:
假设words.txt为:
the
an
linux
ubuntu
life
good
breeze
要洗牌,请执行以下操作:
$ shuf words.txt
这将把打乱的行扔到标准输出;所以,你必须将它管道到一个输出文件,就像:
$ shuf words.txt > shuffled_words.txt
一次这样的洗牌可能会产生:
breeze
the
linux
an
ubuntu
good
life
python的一行代码:
python -c "import random, sys; lines = open(sys.argv[1]).readlines(); random.shuffle(lines); print ''.join(lines)," myFile
如果只打印单个随机行:
python -c "import random, sys; print random.choice(open(sys.argv[1]).readlines())," myFile
但是请参阅这篇文章了解python的random.shuffle()的缺点。它不能很好地处理很多(超过2080个)元素。
简单的基于awk的函数将完成这项工作:
shuffle() {
awk 'BEGIN{srand();} {printf "%06d %s\n", rand()*1000000, $0;}' | sort -n | cut -c8-
}
用法:
any_command | shuffle
这应该可以在几乎任何UNIX上工作。在Linux、Solaris和HP-UX上测试。
更新:
注意,前导零(%06d)和rand()乘法使它在sort不理解数字的系统上也能正常工作。它可以通过字典顺序(也就是普通字符串比较)进行排序。