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

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


当前回答

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

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

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

希望这能有所帮助。

其他回答

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

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

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

希望这能有所帮助。

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

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

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

另一种awk变体:

#!/usr/bin/awk -f
# usage:
# awk -f randomize_lines.awk lines.txt
# usage after "chmod +x randomize_lines.awk":
# randomize_lines.awk lines.txt

BEGIN {
  FS = "\n";
  srand();
}

{
  lines[ rand()] = $0;
}

END {
  for( k in lines ){
    print lines[k];
  }
}

尚未被提及:

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