Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

I've got a directory that contains directories that contain directories that contain files. I'd like to select two files at random from each leaf directory. I found this question about selecting from a single directory, but running it in each of several hundred directories would be a pain.

share|improve this question
    
Do you strictly want to enumerate files like dir/sub1/subsub1/file1, or can the depth vary from one leaf directory to another? –  Gilles Jun 1 at 21:41
    
Strictly full-depth. If the leaf directories are anywhere else, it means something in my music collection isn't sorted correctly. –  Mark Jun 1 at 21:44

2 Answers 2

up vote 3 down vote accepted

With a fixed depth of the directory structure (per your description, a directory with subsubdirectories with files), you could do something like:

for subsubdir in "$directory"/*/*/
do
    find "$subsubdir" -type f | shuf -n 2
done | shuf

The final | shuf in the assumption that you want the list to be randomized as a whole, and not sorted by directory. Otherwise just drop it.

If you expect newlines in your filenames, you can switch to zero-terminated list of files.

share|improve this answer
    
Please note that find "$dir" -type f will also find files in subdirectories. Add -maxdepth 1 to prevent that. –  lcd047 Jun 1 at 7:08
    
@lcd047 if there are subdirectories, the result is not what he wanted anyhow. naturally there aren't supposed to be any subdirectories (beyond a fixed depth determined by */*/*/) in this approach. –  frostschutz Jun 1 at 12:13
    
edited the answer, maybe this makes the intention clearer –  frostschutz Jun 1 at 12:22

You can do it like this:

find /some/dir -type d -not -empty -exec sh -c 'find "$1" -maxdepth 1 -type f | shuf -n 2' sh {} \;

This isn't necessarily the most efficient way of doing it though. :)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.