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

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


当前回答

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

其他回答

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

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

我们有一整套方案来完成这项工作:

sudo apt-get install randomize-lines

例子:

创建一个有序的数字列表,并保存到1000.txt:

seq 1000 > 1000.txt

要洗牌,只需使用

rl 1000.txt

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

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

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

我使用了一个小perl脚本,我称之为“unsort”:

#!/usr/bin/perl
use List::Util 'shuffle';
@list = <STDIN>;
print shuffle(@list);

我也有一个null分隔的版本,称为“unsort0”…方便使用find -print0等。

PS:我也投票给了“shuf”,我不知道现在coreutils有这个词……如果您的系统没有'shuf',上述方法可能仍然有用。