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

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


当前回答

这是第一次尝试,对编码器来说很容易,但对CPU来说很难,它在每行前加上一个随机数,对它们进行排序,然后从每行中剥离随机数。实际上,这些行是随机排序的:

cat myfile | awk 'BEGIN{srand();}{print rand()"\t"$0}' | sort -k1 -n | cut -f2- > myfile.shuffled

其他回答

尚未被提及:

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

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

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

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

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

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

你可以使用洗牌。至少在某些系统上(似乎不在POSIX中)。

正如jleedev指出的:sort -R可能也是一个选项。至少在某些系统上;好吧,你懂的。已经指出sort -R并不真正洗牌,而是根据项的哈希值进行排序。

[编者注:sort -R几乎是洗牌,除了重复的行/排序键总是彼此挨着。换句话说:只有唯一的输入行/键才是真正的shuffle。虽然输出顺序确实是由哈希值决定的,但随机性来自于选择随机哈希函数-参见手册。