random files from directory

random file from directory

random files from directory

Get Random Files From Directory Using Shell Script

Random files from directory is most sought after operation specially when working with files. You may be creating video from image, analyzing sample data and more.

Shell scripting has a lot to offer, not only random files from directory. The cool thing about shell script is, it is more native and fast.

I am working on generating videos from selected images and I needed to have ability to select random files from the given folder.

Do I have other options other than shell scripting

Of course. You do random files from directory problem solved using other programming languages. Almost all languages have file manipulation libraries that you can take advantage of.

But, I would prefer the bash script for for simplicity and speed.

How to get random files from directory using shell script

In this tutorial, I will show you how to copy only random files from directory to another directory.

Here is the code to get random files from directory and copy it to another directory


#!/bin/bash

#How many random files to be pulled
random_file_size=20

#read from source file and randomly populate images
images=(/PATH/TO/THE/SOURCE/FOLDER/*.jpg)

i=0
while [ ${i} -le ${random_file_size} ]
do
    cp ${images[RANDOM % ${#images[@]}]} .
    ((i++))
done

Save the above file as random.sh

How to run the code

Go to your terminal and run
bash random.sh

The above code all you need to copy random files from source directory to destination directory . Now, let’s see what each line means.

The #!/bin/bash tells the bash will be responsible for running this script and it tells what type it is. Usually read as “shibang”.

Then, the random_file_size is the variable holding how much file we want to pick from the source. This can later be passed from the command line.

We have the while loop that will be copying the random file to the directory until we hit 20, in this example.

More @ here

Listing all the files from specific revision in mercurial

enabling locate on mac OSX – finding files easily

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*