3

I would like to rename all of my files of my USB device randomly. Indeed, in my car, my tuner has not the random function.

I think I can do it with PHP ... but I'm pretty sure it is possible to do something shorter in shell script, right?

An idea?

2 Answers 2

3

You can add a random number of equal width as prefix, that's what I'm doing to randomize my audio files:

for i in *; do mv "$i" "$(seq -w 0 999 | shuf -n 1)_$i"; done
4
  • No, this doesn't work: this is a convoluted way of generating a random number for each input, and there is a risk of collision. Aug 21, 2012 at 23:43
  • Yes there is a risk of collision, but this doesn't matter for his use case. Only the random prefix might occur more than once, not the whole file name.
    – scai
    Aug 22, 2012 at 4:59
  • It's probably not that important given the use case, but the resulting output is slightly biased towards lexicographic order of file names. E.g. given files a.mp3, b.mp3 and c.mp3, the order a,b,c is slightly more likely than a,c,b or b,a,c or b,c,a or c,a,b which are slightly more likely than c,b,a. Aug 22, 2012 at 7:16
  • Thank you for your snippet. Even if the collision is not important, the method of Gilles seems cleaner. But thank you for your intervention
    – Raphaël
    Aug 23, 2012 at 8:03
2

Assuming that you are running Linux, that you want to randomly order all files in the current directory and that no file name contains a newline:

printf '%s\n' * | shuf | nl -n rz -s - |
while IFS= read -r name; do
  mv -- "${name#*-}" "$name"
done

The printf command prints the file names, one per line. shuf applies a random permutation to the input lines. nl adds prefixes like 000001-, 000002-, etc. to each line. The while loop iterates over all the lines. The mv command renames foo.mp3 to 000001-foo.mp3, etc.

1
  • Oh thank you for your help. I try that tonight ! It seems to be the best way without any risk of collision
    – Raphaël
    Aug 23, 2012 at 8:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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