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

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


当前回答

如果你安装了Scala,这里有一行代码来洗牌输入:

ls -1 | scala -e 'for (l <- util.Random.shuffle(io.Source.stdin.getLines.toList)) println(l)'

其他回答

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

如果你像我一样来这里寻找一个替代的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

简单的基于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不理解数字的系统上也能正常工作。它可以通过字典顺序(也就是普通字符串比较)进行排序。

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

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

在windows下,您可以尝试此批处理文件来帮助您洗牌data.txt,批处理代码的用法是

C:\> type list.txt | shuffle.bat > maclist_temp.txt

发出这个命令后,maclist_temp.txt将包含一个随机的行列表。

希望这能有所帮助。