Dion Moult Seriously who ever reads this description.

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.

Related posts:

  1. Top 10 Windows Mobile Applications
  2. Free, legal music for all.
  3. The state of vendor lock-in on handheld services?


7 Comments

Gen2ly says: (13 January 2010)

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.

hari says: (13 January 2010)

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.

lefty.crupps says: (13 January 2010)

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).

Dion Moult says: (13 January 2010)

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 ;)

Links 13/1/2010: Linux 2.6.33 RC4, Zenwalk 6.2 Reviewed | Boycott Novell says: (14 January 2010)

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

p. says: (14 January 2010)

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

Dion Moult says: (14 January 2010)

真的吗?

Leave a Comment