我想随机洗牌文本文件的行,并创建一个新文件。该文件可能有几千行。

我如何用cat, awk, cut等做到这一点?


当前回答

Ruby增值:

ls | ruby -e 'puts STDIN.readlines.shuffle'

其他回答

Ruby增值:

ls | ruby -e 'puts STDIN.readlines.shuffle'

这个bash函数有最小的依赖关系(只有sort和bash):

shuf() {
while read -r x;do
    echo $RANDOM$'\x1f'$x
done | sort |
while IFS=$'\x1f' read -r x y;do
    echo $y
done
}

一种简单而直观的方法是使用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

基于scai的答案的Python一行,但是a)接受stdin, b)使结果与seed可重复,c)只选出所有行的200行。

$ cat file | python -c "import random, sys; 
  random.seed(100); print ''.join(random.sample(sys.stdin.readlines(), 200))," \
  > 200lines.txt

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个)元素。