Re: random lines
"Martin F. Krafft" <madduck@madduck.net> writes:
> do you guys know of a smart way to access random lines in a file?
Hmm, here's a really quick & dirty hack:
$ cat data.txt
foo
bar
baz
quux
$ randline() { head -$(($RANDOM % $(wc -l < $1) + 1)) $1 | tail -1; }
$ randline data.txt
quux
$ randline data.txt
foo
$
Perhaps you're interested in the following code ('shuffle'), which i
got from somebody:
--------------------------------
#!/usr/bin/perl
sub shuffle {
@arr = @_;
$i = @arr -1 ;
while($i >= 1) {
$t = int(rand($i+1));
$h = $arr[$t];
$arr[$t] = $arr[$i];
$arr[$i] = $h;
$i--;
}
for $line (@arr){
print $line;
}
}
srand;
shuffle <>;
--------------------------------
It simply prints out the input lines shuffled.
moritz
--
Moritz Schulte <moritz@chaosdorf.de> http://www.chaosdorf.de/moritz/
Debian/GNU supporter - http://www.debian.org/ http://www.gnu.org/
GPG fingerprint = 3A14 3923 15BE FD57 FC06 B501 0841 2D7B 6F98 4199
Reply to: