How can I select random files from a directory in bash?
Here's a script that uses GNU sort's random option:
ls |sort -R |tail -$N |while read file; do
# Something involving $file, or you can leave
# off the while to just get the filenames
done
select random file from directory
select random file from directory
private string getrandomfile2(string path)
{
string file = null;
if (!string.IsNullOrEmpty(path))
{
var extensions = new string[] { ".png", ".jpg", ".gif" };
try
{
var di = new DirectoryInfo(path);
var rgFiles = di.GetFiles("*.*").Where( f => extensions.Contains( f.Extension.ToLower()));
Random R = new Random();
file = rgFiles.ElementAt(R.Next(0,rgFiles.Count())).FullName;
}
// probably should only catch specific exceptions
// throwable by the above methods.
catch {}
}
return file;
}
How do I select a random file from a directory?
use the shuf
command to create a random shuffle and head -1
to pick the top one
ls -1 *.png | shuf | head -1
or
ls -1 *.png | shuf -n 1
Best way to choose a random file from a directory
import os, random
random.choice(os.listdir("C:\\")) #change dir name to whatever
Regarding your edited question: first, I assume you know the risks of using a dircache
, as well as the fact that it is deprecated since 2.6, and removed in 3.0.
Second of all, I don't see where any race condition exists here. Your dircache
object is basically immutable (after directory listing is cached, it is never read again), so no harm in concurrent reads from it.
Other than that, I do not understand why you see any problem with this solution. It is fine.
Pick a random file from a directory in Java
- Create an
array
of the files within the given directory usingFile.listFiles()
. - Select a file based on a random index from this array.
That can be done with an instance of theRandom
class, usingRandom.nextInt(int bound)
, wherebound
, in this case, is the amount of files in thearray
, thus the array's length.
Example:
File[] files = dir.listFiles();
Random rand = new Random();
File file = files[rand.nextInt(files.length)];
Select random file from directory
You can use glob to get all files in a directory, and then take a random element from that array. A function like this would do it for you:
function random_pic($dir = 'uploads')
{
$files = glob($dir . '/*.*');
$file = array_rand($files);
return $files[$file];
}
Best way to choose a random file from a directory in a shell script
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.
Pulling random files out of a folder for sampling
I was unable to get the other methods to work easily with my code, but I came up with this.
output_folder = 'C:/path/to/folder'
for x in range(int(len(files) *.1)):
to_copy = choice(files)
shutil.copy(os.path.join(subdir, to_copy), output_folder)
Related Topics
PHP Datetime() Class, Change First Day of the Week to Monday
PHP How to Write Data to Middle of File Without Rewriting File
MySQL Select from Tables Based on Multiple Rows
PHP Mail Special Characters Utf8
Changing Woocommerce Cart Item Names
Round to Max Thousand, Hundred etc in PHP
How to Create Codeigniter Language Files from Database
What Causes an Http 405 "Invalid Method (Http Verb)" Error When Posting a Form to PHP on Iis
What Does the B in Front of String Literals Do
Get Root Node of Xml Doc Using Simplexml
Is PHP's 'Include' a Function or a Statement
Change Date Format (In Db or Output) to Dd/Mm/Yyyy - PHP MySQL
PHP Password_Verify() Hash and Pass Won't Match
How to Escape Single-Quote (Apostrophe) in String Using PHP
Function Eregi() Is Deprecated