JSI Tip 8562. Another way to replace a string in an environment variable.


We have previously used environment variable string substitiution, the CALL command, and the FOR command to replace a sub-string in an environment variable with another sub-string.

I have scripted RepInString.bat as another alternative.

The syntax for using RepInString.bat is:

Call RepInString StringVar FndVar RepVar

Where:

StringVar is the name of the environment variable that you want to search.
FndVar    is the name of the environment variable that contains the sub-string you wish to replace.
RepVar    is the name of the environment variable that contains the replacement sub-string.

Example:

If you have an environment variable name line that may contain one or more occurances of Windows 2000, and you wish to replace these with W2K, then:
set big=Windows 2000
set small=W2K
call repinstring line big small
NOTE: The search is case sensitive.

RepInString.bat contains:

@echo off
if \{%3\}==\{\} @echo Syntax RepInString StringVar FndVar RepVar&goto :EOF
if exist "%TEMP%\RepInString.VBS" goto doit
@echo dim oString, objArgument>"%TEMP%\RepInString.VBS"
@echo Set objArgument = Wscript.Arguments>>"%TEMP%\RepInString.VBS"
@echo P2 = objArgument(1)>>"%TEMP%\RepInString.VBS"
@echo P3 = objArgument(2)>>"%TEMP%\RepInString.VBS"
@echo oString = Replace(objArgument(0), P2, P3)>>"%TEMP%\RepInString.VBS"
@echo Wscript.echo "*:" ^& oString>>"%TEMP%\RepInString.VBS"
:doit
for /f "Tokens=1* Delims=:" %%a in ('call cscript //NOLOGO "%TEMP%\RepInString.VBS" "%%%1%%" "%%%2%%" "%%%3%%"') do (
 set %1=%%b
)



Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish