:: Rem_Bad_Chars.bat Remove non-alphanumeric characters from file names
:: Herbert Kleebauer alt.msdos.batch.nt Saturday, June 29, 2013
@echo off
setlocal enabledelayedexpansion
:: create _.bat with the rename commands to change any non alphnumeric
:: character in filenames to _
:: check the file _.bat and execute if it's o.k.
set tmp1=_tmp1.tmp
set tmp2=_tmp2.tmp
set tmp3=_tmp3.tmp
set tmp4=_tmp4.tmp
echo.>%tmp3%
dir /b >%tmp4%
call :fopen %tmp4%
set n=0
:l0
set rename=false
set oldname=
set newname=
:l1
call :getc_hex char %n%
set /a n=n+1
:l6
if %char%==-1 goto :l5
if %char%==0d goto :l1
if %char%==0a goto :l2
set /a char_dec=0x%char%
set oldname=%oldname% %char%
if %char%==25 set oldname=%oldname% %char%
if %char_dec% equ 46 goto :l4
if %char_dec% equ 95 goto :l4
if %char_dec% lss 48 goto :l3
if %char_dec% leq 57 goto :l4
if %char_dec% lss 65 goto :l3
if %char_dec% leq 90 goto :l4
if %char_dec% lss 97 goto :l3
if %char_dec% leq 122 goto :l4
:l3
::set newname=%newname% 5f
set rename=true
goto :l1
:l4
set newname=%newname% %char%
goto :l1
:l2
if %rename%==false goto :l0
echo 72 65 6e 20 22 %oldname% 22 20 %newname% 0d 0a>>%tmp3%
goto :l0
:l5
:::::::::::::::::::::::::::::::::::::::::::::::::::::
:: convert hexfile tmp3 to binary outfile
certutil -f -decodehex %tmp3% _.bat >nul
if exist %tmp3% del %tmp3%
if exist %tmp4% del %tmp4%
call :fclose
goto :eof
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:fopen
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
set fsize=%~z1
set cache=-1
certutil -f -encodehex %1 %tmp1% 4 >nul
set n=0
if exist %tmp2% del %tmp2%
for /f "tokens=1-16" %%a in (%tmp1%) do (
set /p =%%a%%b%%c%%d%%e%%f%%g%%h%%i%%j%%k%%l%%m%%n%%o%%p<nul >>%tmp2%
set /a n=n+1
if !n!==64 echo.>>%tmp2% & set n=0)
goto :eof
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:fclose
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
del %tmp1%
del %tmp2%
goto :eof
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:getc_hex
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
if %2 GEQ %fsize% set /a %1=-1 & goto :eof
set /a i=%2/1024 & set /a j=2*(%2%%1024)
if %i%==%cache% goto :skip
echo read cache line %i%
set cache=%i%
set skip=
if %i% GEQ 1 set skip="skip=%i%"
for /f %skip% %%i in (%tmp2%) do (
set line=%%i & goto :skip)
:skip
call set %1=%%line:~%j%,2%%
goto :eof