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

Viewed 134024

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?

13 Answers

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

If you want to copy a sample of those files to another folder:

ls | shuf -n 100 | xargs -I % cp % ../samples/

make samples directory first obviously.

If you have more files in your folder, you can use the below piped command I found in unix stackexchange.

find /some/dir/ -type f -print0 | xargs -0 shuf -e -n 8 -z | xargs -0 cp -vt /target/dir/

Here I wanted to copy the files, but if you want to move files or do something else, just change the last command where I have used cp.

Related