Question

I have a bunch of files and I'd like to remove all the characters that are not in the alphabet. So given a filename of "Home - noises (f).txt" i want a result of "Home noises f.txt. the batch file is in the samefolder and it doesnt need to be recursive. this is what i have so far:

@echo ON
SETLOCAL EnableDelayedExpansion
For %%# in (*.*) do (
    Set MyVar=%%~n#
    set MyVar=!MyVar:"-"= !
    REN "%%~n#" "!MyVar!"
    set MyVar=!MyVar:"("= !
    REN "%%~n#" "!MyVar!"
    set MyVar=!MyVar:")"= !
    REN "%%~n#" "!MyVar!"
    echo %%~n#>>text.txt
)
Pause&Exit
Was it helpful?

Solution

@echo off
setlocal EnableDelayedExpansion
set preserve=abcdefghijklmnopqrstuvwxyz 1234567890
for %%a in (*.*) do (
   set "filename=%%~Na"
   call :RemoveChars filename newFilename=
   if "!newFilename!" neq "%%~Na" ren "%%a" "!newFilename!%%~Xa"
)
goto :EOF


:RemoveChars filename newFilename=
set %2=
:nextChar
   set "char=!%1:~0,1!"
   if "!preserve:%char%=!" neq "%preserve%" set "%2=!%2!%char%"
   set "%1=!%1:~1!"
if defined %1 goto nextChar
exit /B

The version below will run much faster than previous one, but requires several modifications in order to manage certain special characters in the remove string.

@echo off
setlocal EnableDelayedExpansion
set remove=@#$()[]
for %%a in (*.*) do (
   set "filename=%%~Na"
   call :RemoveChars filename newFilename=
   if "!newFilename!" neq "%%~Na" ren "%%a" "!newFilename!%%~Xa"
)
goto :EOF


:RemoveChars filename newFilename=
set "%2=!%1!"
set "remove2=!remove!"
:nextChar
   set "char=!remove2:~0,1!"
   set "%2=!%2:%char%=!"
   set "remove2=!remove2:~1!"
if defined remove2 goto nextChar
exit /B

OTHER TIPS

or, with renamer you could run:

$ renamer --regex --find '\W' *

This works really well. Is someone able to integrate this code in the upper solution so it will replace German Umlaute first before deleting other special characters? ä -> ae ü -> ue ö -> oe ß -> ss

I found this:
`

@echo off      
SET VARX=%1%      
SET VARX=%VARX:„=ae%      
SET VARX=%VARX:”=oe%      
SET VARX=%VARX:=ue%      
SET VARX=%VARX:á=ss%      
ECHO %VARX%      
SET VARX=      
pause 

`

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top