How can I select random files from a directory in bash?


Question

I have a directory with about 2000 files. How can I select a random sample of N files through using either a bash script or a list of piped commands?

1
119
7/1/2013 5:14:31 PM

Accepted Answer

Here's a script that uses GNU sort's random option:

ls |sort -R |tail -$N |while read file; do
    # Something involving $file, or you can leave
    # off the while to just get the filenames
done
156
1/5/2009 8:01:13 PM

You can use shuf (from the GNU coreutils package) for that. Just feed it a list of file names and ask it to return the first line from a random permutation:

ls dirname | shuf -n 1
# probably faster and more flexible:
find dirname -type f | shuf -n 1
# etc..

Adjust the -n, --head-count=COUNT value to return the number of wanted lines. For example to return 5 random filenames you would use:

find dirname -type f | shuf -n 5

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon