Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to choose a random file from a directory in a shell script

What is the best way to choose a random file from a directory in a shell script?

Here is my solution in Bash but I would be very interested for a more portable (non-GNU) version for use on Unix proper.

dir='some/directory' file=`/bin/ls -1 "$dir" | sort --random-sort | head -1` path=`readlink --canonicalize "$dir/$file"` # Converts to full path echo "The randomly-selected file is: $path" 

Anybody have any other ideas?

Edit: lhunath makes a good point about parsing ls. I guess it comes down to whether you want to be portable or not. If you have the GNU findutils and coreutils then you can do:

find "$dir" -maxdepth 1 -mindepth 1 -type f -print0 \   | sort --zero-terminated --random-sort \   | sed 's/\d000.*//g/' 

Whew, that was fun! Also it matches my question better since I said "random file". Honsetly though, these days it's hard to imagine a Unix system deployed out there having GNU installed but not Perl 5.

like image 743
JasonSmith Avatar asked Mar 31 '09 15:03

JasonSmith


People also ask

How do I select random files in a folder?

On first run you select to add it to Windows Explorer and find that option available when you right-click in a folder in the file browser. There you find listed the new select random menu option. Selecting it picks a random file that is stored in the directory.

How do you select multiple files in random order?

Click the first file or folder, and then press and hold the Ctrl key. While holding Ctrl , click each of the other files or folders you want to select.


1 Answers

files=(/my/dir/*) printf "%s\n" "${files[RANDOM % ${#files[@]}]}" 

And don't parse ls. Read http://mywiki.wooledge.org/ParsingLs

Edit: Good luck finding a non-bash solution that's reliable. Most will break for certain types of filenames, such as filenames with spaces or newlines or dashes (it's pretty much impossible in pure sh). To do it right without bash, you'd need to fully migrate to awk/perl/python/... without piping that output for further processing or such.

like image 185
lhunath Avatar answered Oct 13 '22 04:10

lhunath