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 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?

share|improve this question

2 Answers 2

up vote 2 down vote accepted

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.

share|improve this answer
    
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 '12 at 8:02

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
share|improve this answer
    
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. –  Gilles Aug 21 '12 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 '12 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. –  Gilles Aug 22 '12 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 '12 at 8:03

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.