Pick random file from ls command.

Lets say I want to pick a random file when I do an "ls" command. I don't have set number of files in each directory.

ls | head -1

This gives me the first one in each directory, is there a way to do the same but pick a random one.

A bit odd, but...

ls | sed $((RANDOM%$(ls | wc -w)+1))!d\;q

or

ls | head -$((RANDOM%$(ls | wc -w)+1)) | tail -1

First one didn't work
ls | sed $((RANDOM%$(ls | wc -w)+1))!d
-bash: !d: event not found

The second one works perfectly. Can you help me understand how it works? thanks.

Hey, you're right!

Works in KSH (on AIX) but not in Bash.

ls | sed -n "$((RANDOM%$(ls | wc -l)+1))p"

(changed wc to use -l)

  • do an ls, and pipe to output to sed
  • get a random number with modulo of the number of files (i.e. pick a number between 1 and the number of files in the directory). $RANDOM is a special variable that returns a "random" number between 0 and 32K-1
  • tell sed not to print anything except that line number (i.e. that file)