2014-03-13 30 views
0

我有一个巨大的文件(数百万行)。我想从中得到一个随机样本,我已经生成了一个唯一的随机数列表,现在我想要得到所有行号与我生成的随机数相匹配的行。获取文件中的行列表

对随机数进行排序不是问题,所以我想我可以把连续数字区分开来,只是在文件中用光标跳转。

我认为我应该使用sedawk

+0

[在Unix命令行中读取随机文件的简单方法是什么?](http://stackoverflow.com/questions/448005/whats-an-easy-way-to-read-random -line-from-a-file-in-unix-command-line) – tripleee

回答

4

你为什么不直接使用shuf获得随机行:

shuf -n NUMBER_OF_LINES file 

$ seq 100 >a # the file "a" contains number 1 to 100, each one in a line 

$ shuf -n 4 a 
54 
46 
30 
53 

$ shuf -n 4 a 
50 
37 
63 
21 

更新

我可以以某种方式存储的行数舒夫选择了? - 皮奥

正如我在How to efficiently get 10% of random lines out of the large file in Linux?一样,你可以做这样的事情:

shuf -i 1-1000 -n 5 > rand_numbers # store the list of numbers 
awk 'FNR==NR {a[$1]; next} {if (FNR in a) print}' list_of_numbers a #print those lines 
+0

哇......我不知道这个:)。我能以某种方式存储shuf选择的行数吗? – Pio

+0

是的,看我的更新:) – fedorqui

+0

如果我存储'wc -l文件名> max',在一个bash脚本中,那么如何才能只获得'wc -l'的第一个元素而不是文件名? – Pio

0

您可以使用awkshuf

shuf file.txt > shuf.txt 
awk '!a[$0]++' shuf.txt > uniqed.txt 

awk是为了去除重复的最佳工具。