0

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
user2313522
  • 205
  • 1
  • 4
  • 10
  • space is not alpha - why is that preserved? what about numbers? – dbenham May 19 '13 at 23:57
  • these would be the characters preserved "abcdefghijklmnopqrstuvwxyz 1234567890" but no "special" characters – user2313522 May 20 '13 at 02:05
  • What about `.`? What happens if the name only consists of "special" characters? What should happen if 2 names collapse into one, like "a&b", "a+b"? – dbenham May 20 '13 at 04:03

3 Answers3

1
@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
Aacini
  • 65,180
  • 12
  • 72
  • 108
0

or, with renamer you could run:

$ renamer --regex --find '\W' *
Lloyd
  • 8,204
  • 2
  • 38
  • 53
0

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 

`

Tom Senner
  • 548
  • 1
  • 6
  • 21