Rename files with ampersand in the name


Dec 7, 2015
I'm trying to rename a bunch of mp3 files. The files are in the format XXX.Artist - Title.mp3. XXX is a sequential number and I'm trying simply to randomly reorder the files. I exchange each file with another one with a random order number. This is the code:

set NumMax=369
for /L %f in (1, 1, %NumMax) (
set R=%@random[1, %NumMax]
set N1=%@right[3,000%f]
set N2=%@right[3,000%R]
if %N1 NE %N2 (
for %g in (%N1*.mp3) (
for %h in (%N2*.mp3) (
set L1=%@eval[%@len[%g]-4]
set L2=%@eval[%@len[%h]-4]
set NN1=%N2.%@right[%L1,%g]
set NN2=%N1.%@right[%L2,%h]
echo ren "%g" "%NN1"
echo ren "%h" "%NN2"

The problem is, some filenames contain "&", for example "174.Katrina & The Waves - Walking on sunshine.mp3", and those name break the functionality. Without ampersands, it works ok:

ren "173.Kansas - Dust in the Wind.mp3" "053.Kansas - Dust in the Wind.mp3"
ren "053.Bruce Springsteen - The River.mp3" "173.Bruce Springsteen - The River.mp3"

but with ampersands:
TCC: C:\Selection\RandomRen.btm [18] Comando desconocido "The"
ren "174.Katrina & The Waves - Walking on sunshine.mp3" "050.Katrina"
ren "050.Bruce Springsteen - Hungry Heart.mp3" "174.Bruce Springsteen - Hungry Heart.mp3"

the problem is, the line:
set NN1=%N2.%@right[%L1,%g]
gets confused with the "&". I've tried using SETDOS /X-4 to disable nested variable expansion but there is no difference

Similar threads