tags:

views:

60

answers:

3

I have a "smart" phone that doesn't seem to have a music shuffle function, so the next best thing is to write a bash script to prepend all filenames in the current directory with a random number.

Is this difficult to do?

Thanks.

+1  A: 

Not really difficult. Something like:

for i in *; do mv "$i" $RANDOM-"$i"; done
zaf
+2  A: 

No, this is not hard to do. It will however mess up your carefully crafted filenames, and might be hard to undo.

You can use $RANDOM as a simple source of random numbers in bash. For your case:

#!/bin/bash
for file in *; do
  mv "$file" $RANDOM-"$file"
done

I didn't test this. You probably want to test this yourself on some small sample to make sure you know what it does.

honk
Also, don't run it more than once on any given set of files, or it'll prepend another number. Nothing like having "1413-426-234235-2-NeverGonnaGiveYouUp.mp3".
cHao
@cHao: Exactly. The whole approach of moving the files is broken. If he could use softlinks in some specific directory and just remove it once he's done. Not sure if his filesystem can do this.
honk
Unfortunately, I don't have access to things like links, since it's just a FAT system. Fortunately, the filenames are more or less meaningless since the important stuff is in ID3 tags.
Reinderien
one can use e.g. `printf "%06d" $RANDOM` to keep the length of random part a constant.
Dummy00001
@cHao: actually, 4-8-15-16-23-42-NeverGonnaGiveYouUp.mp3 would be much worse ;P
ninjalj
+2  A: 

This script will shuffle files and reshuffle them if they've already been shuffled. If you pass it an argument of -u it will unshuffle the files (remove the random prefix).

#!/bin/bash
for file in *.mp3
do
    if [[ -d $file ]]
    then
        continue    # skip directories
    fi
    if [[ $file =~ ^1[0-9]{5}9-(.*).mp3$ ]]    # get basename
    then
        name=${BASH_REMATCH[1]}                # of a previously shuffled file
    else
        name=${file%.mp3}                      # of an unshuffled file
    fi
    if [[ $1 != -u ]]
    then
        mv "$file" "1$(printf "%05d" $RANDOM)9-$name.mp3"    # shuffle
    else
        if [[ ! -e "$file.mp3" ]]
        then
            mv "$file" "$name.mp3"                           # unshuffle
        fi
    fi
done

It uses a fixed-width five digit random number after a "1" and followed by "9-" so the shuffled filenames are of the form: 1ddddd9-filename maybe with spaces - and other stuff.1983.mp3.

If you re-run the script, it will reshuffle the files by changing the random number in the prefix.

The -u argument will remove the 1ddddd9- prefix.

The script requires Bash >= version 3.2.

Dennis Williamson