Search code examples
windowsbatch-filefile-rename

Batch rename issue when dealing with special characters in the filename


I have several hundred *.mp3 files in c:\files. There are all imaginable filenames in there like

  • milad.mp3 (good behaving)
  • hey you.mp3 (space in filename)
  • systemofadown.mp3 (long filename)
  • howdy(1).mp3 (parentheses in filename)

and any combination of the last three conditions. I want to rename the files to 001-test.mp3, 002-mp3, ... It doesn't matter which file gets which name. have written a batch file to do the rename. Here is my code (with line numbers added):

01  rem @echo off
02  cls
03  set _number=%1
04  lfnfor on
05
06  :F1TO10
07  IF NOT EXIST *.mp3. goto end
08  if %_number% gtr 9 goto F10TO100
09  for /f %%a IN ('dir /b *.mp3') do rename %%~na.mp3 00%_number%-test.mp4
10  set /a _number +=1
11  goto F1TO10
12
13  :F10TO100
14  IF NOT EXIST *.mp3. goto end
15  if %_number% gtr 99 goto F100TO1000
16  for /f %%a IN ('dir /b *.mp3') do rename %%~na.mp3 0%_number%-test.mp4
17  set /a _number +=1
18  goto F10TO100
19
20  :F100TO1000
21  IF NOT EXIST *.mp3. goto end
22  if %_number% gtr 999 goto end
23  for /f %%a IN ('dir /b *.mp3') do rename %%~na.mp3 %_number%-test.mp4
24  set /a _number +=1
25  goto F100TO1000
26
27  :end
28  for /f %%a IN ('dir /b *.mp4') do rename %%~na.mp4 %%~na.mp3
29  echo Done

This code works fine for good behaving filenames (i.e. no spaces, no parentheses, no longer than 8 chars long). But if I have even a single file with a bad behaving filename, the script breaks (it loops endlessly until I stop it with Ctrl-C).

The problem is obviously a filename issue. How can this be fixed? Any ideas? I'd greatly appreciate any help.


Solution

  • First of all I would like to thank the friends who offered help through answers. But none was what I was looking for. Actually I arrived at a flawlessly working script using help provided by Spire posted as an answer to this question.

    Here is the final code: (no need for line numbers this time)

    rem @echo off
    cls
    set _number=%1
    
    :F1TO10
    IF NOT EXIST *.mp3. goto end
    if %_number% gtr 9 goto F10TO100
    for /f "usebackq delims=" %%x in (`dir /b *.mp3`) do rename %%~nsx.mp3 00%_number%-test.mp9
    set /a _number +=1
    goto F1TO10
    
    :F10TO100
    IF NOT EXIST *.mp3. goto end
    if %_number% gtr 99 goto F100TO1000
    for /f "usebackq delims=" %%x in (`dir /b *.mp3`) do rename %%~nsx.mp3 0%_number%-test.mp9
    set /a _number +=1
    goto F10TO100
    
    :F100TO1000
    IF NOT EXIST *.mp3. goto end
    if %_number% gtr 999 goto end
    for /f "usebackq delims=" %%x in (`dir /b *.mp3`) do rename %%~nsx.mp3 %_number%-test.mp9
    set /a _number +=1
    goto F100TO1000
    
    :end
    for /f %%a IN ('dir /b *.mp9') do rename %%~na.mp9 %%~na.mp3
    echo Done.