|
Answer» Win XP Home SP.3+
Why does the first part of the script work as expected but the SECOND does not?
Thanks.
Code: [Select]echo off cls setlocal enabledelayedexpansion
set line6=now is the time ( for all good ?
:: Change all ( chars in line6 to -.
for /f "tokens=*" %%a in ("%line6%") do ( set line=%%a echo Line=!line!
set line=!line:(=-! echo Line=!line! ) echo.&echo.
set line6=now is the time * for all good ?
:: Change all * chrs in line6 to -.
for /f "tokens=*" %%a in ("%line6%") do ( set line=%%a echo Line=!line!
set line=!line:*=-! echo Line=!line! )
As you have noticed, the asterisk is a special character in NT family (cmd.exe) command language. It is used as the multiplication operator in arithmetic. See SET command help by typing SET /? at the prompt. The string replace operation USING SET will fail if the first (or only) character of the search string is an asterisk (or an equals sign).
I can think of 2 possible solutions
(1) Replace characters one by one in a loop
Code: [Select]echo off
set line6=now is the time * for all good ?
REM Set your asterisk replacement here set "replace=-"
REM Clear an output string and a counter set "output=" set j=0
REM loop through the string replacing any asterisk with replace :loop call set char=%%line6:~%j%,1%% if "%char%"=="*" set char=%replace% set output=%output%%char% set /a j+=1 if not "%char%"=="" goto loop
REM display input and output strings echo Input %Line6% echo Output %output% (2) Create a temporary one line Visual Basic Script which uses that language's string replace function.
Code: [Select]echo off REM Create script Echo Wscript.Echo Replace(Wscript.Arguments(0),Wscript.Arguments(1),Wscript.Arguments(2)) > RepString.vbs
set line6=now is the time * for all good ?
REM Run script using Cscript engine and capture output for /f "delims=" %%A in ( ' cscript //nologo RepString.vbs "%line6%" "*" "-" ' ) do set output=%%A
REM Show result echo Input %line6% echo Output %output%
REM Clean up del RepString.vbs
By the way, we are not using MS-DOS here and using the double COLON ( to start a comment line is non-standard and unsupported and will break a script if it is used inside parentheses such as in FOR loops.
Salmon Trout, thankyou. I have your batch script working perfectly and will now try to integrate it into another script. I must check for and amend all chars which are invalid in filenames.
Your assistance is very much appreciated.
Also thanks for the warning on the use of double colon instead of Rem.
Betty.You could loop through a BUNCH of the remaining special characters with a FOR Loop.
Code: [Select]For %%I In (^| ^& ^< ^> ^^ + ^( ^) \ / . # $ { } [ ] ' ; : , ? ` ^%% ^") Do Set line=!line:%%I=!
|