Search code examples
windowsbatch-fileunicodefilenamesbatch-rename

Batch Removal of multiple Unicode codes (ie. %20) from filenames


I routinely work with file groups of 30,000-50,000 individual files, many of which have unicode codes included in the file name (ie %20, %5a, %5b, etc). To properly process these files, I need to replace these characters with an underscore.

I have a script I use to replace one of these codes at a time, but have to run several script to clean the lists and invariably miss some.

The script I use, with %20 as an example is as follows:

@echo off
setlocal EnableDelayedExpansion

for /f "delims=" %%I in ('dir /b ^| find "%20"') do (
set var01=%%I
set var02=!var01:%%5c=_!
call :ren
)
:ren
ren %var01% %var02%

This works fine for each code but I'd like to be able to find %** to find all of the codes and replace them at once. Is this something that can be done through a reasonably simple bat or would I need a more specialized tool?

Thanks for any assistance


Solution

  • @echo off
    setlocal EnableDelayedExpansion
    :: remove variables starting $ 
    For %%b IN ($) DO FOR  /F "delims==" %%a In ('set %%b 2^>Nul') DO SET "%%a="
    FOR %%a IN (0 1 2 3 4 5 6 7 8 9 a b c d e f) DO (
     FOR %%b IN (0 1 2 3 4 5 6 7 8 9 a b c d e f) DO (
      SET "$%%a%%b=%%%%a%%b"
     )
    )
    for /f "delims=" %%I in ('dir /b /a-d^| find "%%"') do (
     SET "var1=%%I"
     FOR /f "tokens=2delims==" %%x IN ('set $') DO SET "var1=!var1:%%x=_!"
     IF "%%I" neq "!var1!" ECHO(REN "%%I" "!var1!"
    )
    GOTO :EOF
    

    This should fix your problem.

    The required REN commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(REN to REN to actually rename the files.