Tech tip #4: Copy a random set of files from a directory.

More for archival purposes than anything, today I wanted to copy some songs out of my serious mess of a music "collection" onto my microSD card. I didn’t want to have to choose and I haven’t rated my songs so that wouldn’t help. Instead I wanted a random selection of songs. I’m not a bashmaster (absolutely pathetic at it, actually) but this is what I ended up using – after symlinking all of the various directories I had my files under together:

find -L /home/drive/music -type f -name "*.mp3" | sort -R | tail -n100 | while read file; do cp "$file" /media/disk/music/; done

-n100 represents how many files are going to be copied. Hope it helps somebody! Of course any improvements are welcome.

Spread the love
Tagged: , , , , , , ,


  1. Hey, nice tip. I would have got stuck at the piping to loop part. ‘read’ I’ve seen but haven’t had need to use yet (read line from standard input). Hmm, very clever.

  2. Personally I prefer to write my automated scripts in Python. More readable, convenient and almost as portable as Perl – though not as portable as shell scripts.

  3. What about that command makes the selection random? Looking at it, it appears to me that every run would produce the same files, but whjen I run it the output is indeed random and I am not seeing how (I am also not a bashmaster but I try to understand it whenever I can).

  4. lefty.crupps, The find command is straightfoward and returns a list of mp3 files with their full path, searched through all symlinked directories via the -L flag. The sort -R does the magic, man sort will tell you that that reorders the list. Then of course we simply tail the list to pick the last 100 in that list (which’ll change due to the sort -R every time) and pass it on to the loop.

    hari, I’d probably do that too but I’m much less familiar with it ;)

  5. If the language of the web is Chinese, you’d probably wouldn’t exist here.(This house is all against any form of racism.) :)

Leave a Reply

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