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

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


当前回答

Perl一行程序是Maxim解决方案的简单版本

perl -MList::Util=shuffle -e 'print shuffle(<STDIN>);' < myfile

其他回答

这是一个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'

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脚本

awk 'BEGIN{srand() }
{ lines[++d]=$0 }
END{
    while (1){
    if (e==d) {break}
        RANDOM = int(1 + rand() * d)
        if ( RANDOM in lines  ){
            print lines[RANDOM]
            delete lines[RANDOM]
            ++e
        }
    }
}' file

输出

$ cat file
1
2
3
4
5
6
7
8
9
10

$ ./shell.sh
7
5
10
9
6
8
2
1
3
4

尚未被提及:

unsort的util。语法(有点面向播放列表): unsort [-hvrpncmMsz0l][——help][——version][——random][——heuristic] [——identity][——filenames[=profile]][——separator sep][——concatenate] [——合并][——merge-random][——种子整数][——字符串作为][——零] [——linefeed][文件…] Msort可以逐行洗牌,但它通常是多余的: Seq 10 | msort -jq -b -l -n 1 -c r

基于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