Select 行重复使用标准命令行工具

Select lines with repetition using standard command-line tools

给定一个包含字符串的文本文件,我想随机绘制行并替换(重复)。

我知道可以使用 "shuf" 命令有效地洗牌。什么是标准的 linux 命令行工具来绘制 with 重复的线条?

我目前的方法是 Python 脚本,它基本上生成 [1,N] 范围内的随机数,其中 N 是行数。生成的随机数(整数)用于索引字符串列表,然后打印。

这是我的 Python 脚本:

  1 #!/usr/bin/env python
  2 
  3 from random import random
  4 import sys
  5 
  6 fname = sys.argv[1]
  7 
  8 with open( fname, 'r' ) as f:
  9         lines = f.readlines()
 10 lines = [ s.strip("\n") for s in lines ]
 11 
 12 nlines = len( lines )
 13 
 14 for i in range( nlines ):
 15         idx = round(random()*nlines)
 16         idx = int( idx )
 17         print lines[ idx ]

示例文件是:

a
b
c
d
e
f
g
h

运行 示例脚本的结果是:

c
b
f
b
c
c
b
d

shuf 的现代版本提供了 -r 重复选项。例如:

$ cat input
1
2
3
4
5
$ shuf -n 5 -r input
3
2
5
3
3
$ shuf --version
shuf (GNU coreutils) 8.23

shuf 的早期版本可能缺少 -r

备选方案:使用 awk

$ awk '{a[NR]=[=11=]} END{srand();for (i=1;i<=NR;i++)print a[int(1+NR*rand())]}' input
4
3
1
2
3