First, if you're going to be doing DOS scripting, AND if you have control over filenames/directory names, then please avoid anything that could be considered a special character.
If you must deal with special characters, your best idea is to use something other than DOS. It's often just way too difficult to get it all to work -- especially with 1 giant "generic" script.
BUT, in general, you can escape special characters using ^
and you can add it in using substring substitution like this:
set "filename=%1"
echo %filename:!=^!%
Note -- there's an extra % in this line:
FOR /F "delims=" %%f IN ('DIR /S /A-D /B "%searchIn%\*%FindChr%*.*%"') DO (
Now, for the %, all you need to do is change this line like this:
SET FindChr=%%
For the "!" character, you can't use delayedexpansion. This works:
Code: Select all
@ECHO OFF
::SETLOCAL EnableDelayedExpansion
SET searchIn=C:\tmp
SET FindChr=!
SET ReplaceChr=_
FOR /F "delims=" %%f IN ('DIR /A-D /S /B "%searchIn%\*%FindChr%*.*"') DO (
SET "var=%%~nf%%~xf"
call SET "var=%%var:%FindChr%=%ReplaceChr%%%"
call ECHO "%%f" -- "%%var%%"
call Ren "%%f" "%%var%%"
)
I couldn't get the -> part to translate properly so I changed it to --
For the ~ character, you'll have to change the for command like this:
FOR /F "delims=" %%f IN ('DIR /S /A-D /B "%searchIn%\*"^|find "~"') DO (
AND you'll have to add a ^. So far this is all I could get to work for a ~
Code: Select all
::@ECHO OFF
::SETLOCAL EnableDelayedExpansion
SET searchIn=C:\tmp
SET FindChr=^~
SET ReplaceChr=_
FOR /F "delims=" %%f IN ('DIR /A-D /S /B "%searchIn%\"^|find "%findchr%"') DO (
SET "var=%%~nf%%~xf"
call SET "var=%%var:^%FindChr%=%ReplaceChr%%%"
call ECHO "%%f" -- "%%var%%"
call Ren "%%f" "%%var%%"
)
For the = character, I think the only way to do it is to go character by character in a loop something like this (completely untested):
Code: Select all
set "origfilename=test=test.txt"
set "oldfilename=%origfilename%"
set "findchr=="
set "replacechr=_"
:loop
if "%oldfilename:~0,1%"=="%findchr%" (
set "newfilename=%newfilename%%replacechr%"
) else (
set "newfilename=%newfilename%%oldfilename:~0,1%"
)
set "oldfilename=%oldfilename:~1,99999%"
if defined oldfilename goto :loop
ren "%origfilename%" "%newfilename%"
In fact, something like this last one might work for most special characters. The % will have to be doubled %%