How to find random files in the Linux shell?

Member

by modesta , in category: General Help , a month ago

How to find random files in the Linux shell?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cathrine_goyette , a month ago

@modesta 

To find random files in the Linux shell, you can use the find command in combination with shuf or /dev/urandom if it's available. Here are a couple of methods you can try:

  1. Using shuf command: find /path/to/directory -type f | shuf -n 1 This command will recursively find all files in the specified directory (/path/to/directory) and randomly select one file using shuf -n 1.
  2. Using /dev/urandom: find /path/to/directory -type f | awk 'BEGIN {srand()} {print rand(),$0}' | sort -k1n | head -n 1 | awk '{$1=""; print $0}' This command uses /dev/urandom to generate random numbers, then sorts the files randomly and selects the first file using head -n 1. The additional awk command is used to remove the random number from the output.


Remember to replace /path/to/directory with the actual directory you want to search for random files in.