我想随机洗牌文本文件的行,并创建一个新文件。该文件可能有几千行。
我如何用cat, awk, cut等做到这一点?
我想随机洗牌文本文件的行,并创建一个新文件。该文件可能有几千行。
我如何用cat, awk, cut等做到这一点?
当前回答
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个)元素。
其他回答
这是一个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'
如果你像我一样来这里寻找一个替代的macOS洗牌,那么使用随机行。
安装随机行(自制)包,其中有一个rl命令,具有类似于shuf的功能。
酿造安装随机行
Usage: rl [OPTION]... [FILE]...
Randomize the lines of a file (or stdin).
-c, --count=N select N lines from the file
-r, --reselect lines may be selected multiple times
-o, --output=FILE
send output to file
-d, --delimiter=DELIM
specify line delimiter (one character)
-0, --null set line delimiter to null character
(useful with find -print0)
-n, --line-number
print line number with output lines
-q, --quiet, --silent
do not output any errors or warnings
-h, --help display this help and exit
-V, --version output version information and exit
这是第一次尝试,对编码器来说很容易,但对CPU来说很难,它在每行前加上一个随机数,对它们进行排序,然后从每行中剥离随机数。实际上,这些行是随机排序的:
cat myfile | awk 'BEGIN{srand();}{print rand()"\t"$0}' | sort -k1 -n | cut -f2- > myfile.shuffled
我使用了一个小perl脚本,我称之为“unsort”:
#!/usr/bin/perl
use List::Util 'shuffle';
@list = <STDIN>;
print shuffle(@list);
我也有一个null分隔的版本,称为“unsort0”…方便使用find -print0等。
PS:我也投票给了“shuf”,我不知道现在coreutils有这个词……如果您的系统没有'shuf',上述方法可能仍然有用。
如果你安装了Scala,这里有一行代码来洗牌输入:
ls -1 | scala -e 'for (l <- util.Random.shuffle(io.Source.stdin.getLines.toList)) println(l)'