Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I get exactly n random lines from a file with Perl?
    primarykey
    data
    text
    <p>Following up on <a href="https://stackoverflow.com/questions/448005/whats-an-easy-way-to-read-random-line-from-a-file-in-unix-command-line" title="What’s an easy way to read random line from a file in Unix command line?">this</a> question, I need to get exactly <code>n</code> lines at random out of a file (or <code>stdin</code>). This would be similar to <code>head</code> or <code>tail</code>, except I want some from the middle.</p> <p>Now, other than looping over the file with the solutions to the linked question, what's the best way to get exactly <code>n</code> lines in one run?</p> <p>For reference, I tried this:</p> <pre><code>#!/usr/bin/perl -w use strict; my $ratio = shift; print $ratio, "\n"; while () { print if ((int rand $ratio) == 1); } </code></pre> <p>where <code>$ratio</code> is the rough percentage of lines I want. For instance, if I want 1 in 10 lines:</p> <pre><code>random_select 10 a.list </code></pre> <p>However, this doesn't give me an exact amount:</p> <pre><code>aaa> foreach i ( 0 1 2 3 4 5 6 7 8 9 ) foreach? random_select 10 a.list | wc -l foreach? end 4739 4865 4739 4889 4934 4809 4712 4842 4814 4817 </code></pre> <p>The other thought I had was slurping the input file and then choosing <code>n</code> at random from the array, but that's a problem if I have a really big file.</p> <p>Any ideas?</p> <p><strong>Edit:</strong> This is an exact duplicate of <a href="https://stackoverflow.com/questions/692312/randomly-pick-lines-from-a-file-without-slurping-it-with-unix" title="Randomly Pick Lines From a File Without Slurping It With Unix">this</a> question.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload