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

我如何用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

其他回答

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

sudo apt-get install randomize-lines

例子:

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

seq 1000 > 1000.txt

要洗牌,只需使用

rl 1000.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

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

#!/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];
  }
}

这是一个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'