here's my random file script to recursively choose a number of random files matching a regex from a directory or list of directories
#!/usr/bin/env perl # recursively choose a number of files optionally matchinng a regex # from a directory or list of directories. defaults to cwd. # outputs absolute paths by default, relative with -r # use like so: # randomfile -n 23 -p \(mp3\|ogg\|flac\)$ ~/music ~/music2 use strict; use warnings; use Getopt::Long; use Cwd; use File::Random qw/random_file/; use File::Spec; my $pat = '^.+$'; my $num = 1; my $relative = 0; GetOptions( 'p|pattern=s' => \$pat, 'n|number=i' => \$num, 'r|relative' => \$relative, ); while ($num) { my $random_file; my $dir; do { $dir = $ARGV[rand @ARGV] or cwd(); $random_file = random_file( -dir => $dir, -check => qr/$pat/, -recursive => 1); } until $random_file; $random_file = "$dir/$random_file"; $random_file = File::Spec->abs2rel($random_file) if $relative; print "$random_file\n"; --$num; }

Replies are listed 'Best First'.
Re: random file script
by i5513 (Pilgrim) on Feb 04, 2015 at 12:35 UTC
    On linux, it is simple to do it, sort command can randomize with -R flag:
    find . -name "*mp3" | sort -R | head -n 5
    An alternative can be using shuf:
    find . -name "*mp3" | shuf | tail -n 5
    Using perl:
    find . -name "*mp3" | perl -MList::Util=shuffle -e 'print shuffle <>' + | head -n 4
    Hint: You can wrap that line with a shell function
      The one liners are always impressive, but the long hand version looks like a more respectable game of golf :P
        You can always add it to your profile, so not long lines are necessary :) :
        function playlist { find /home/javi/Música/ -type f | grep "$1" | shuf | head -n $2; } $ playlist mp3 10
        Long lines on shell are the unix spirit :P . Tools that only have a mission and glue magic