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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With