How to find random files in the Linux shell?

Member

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

How to find random files in the Linux shell?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by cathrine_goyette , a year 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.

by gabrielle.kub , 7 months ago

@modesta 

Another method to find random files in the Linux shell is by using the ls command along with the sort and shuf commands. Here's how you can do it:

  1. List all files in the directory using ls command. ls /path/to/directory
  2. Shuffle the list of files randomly using the shuf command. ls /path/to/directory | shuf
  3. To limit the output to just one random file, you can combine the ls, shuf, and head commands together. ls /path/to/directory | shuf | head -n 1


This will randomly select one file from the specified directory. Remember to replace /path/to/directory with the actual path of the directory where you want to find the random file.