I\'m writing a simple script to substitute text in an environment variable with other text. The trouble I get is with the substituted or substituted text being pulled from o
Recently I came accross the same situation..As said earlier, I used like below and worked...
set filearg=C:\data\dev\log\process
set env=C:\data\dev
REM I wanted \log\process as output
SETLOCAL enabledelayedexpansion
set str2=!filearg:%env%=!
echo Output : %str2%
echo.
endlocal
Output :
\log\process
It worked..!!
And... How about this?
@echo off
setlocal enabledelayedexpansion
set str=The fat cat
set f=fat
set t=thin
echo.
echo f = [%f%]
echo t = [%t%]
echo.
echo str = [%str%]
set str=!str:%f%=%t%!
echo str:f=t = [%str%]
Nifty eh?
Use CALL. Put the following in a batch script and run it:
set a=The fat cat
set b=fat
set c=thin
REM To replace "%b%" with "%c%" in "%a%", we can do:
call set a=%%a:%b%^=%c%%%
echo %a%
pause
As stated here, we use the fact that:
CALL internal_cmd
...
internal_cmd Run an internal command, first expanding any variables in the argument.
In our case internal_cmd is initially set a=%%a:%b%^=%c%%%.
After expansion internal_cmd becomes set a=%a:fat=thin%.
Thus, in our case running
call set a=%%a:%b%^=%c%%%
is equivalent to running:
set a=%a:fat=thin%.
Please try the following:
Copy and paste the code into Notepad and save it as a batch file.
@echo off
setlocal enabledelayedexpansion
set str=The fat cat
set f=fat
echo.
echo f = [%f%]
echo.
echo str = [%str%]
set str=!str:%f%=thin!
echo str:f=thin = [%str%]
I hope you're convinced!
The problem with:
echo %a:%c%=thin%
is that it tries to expand two variables: a:
and =thin
with a c
constant string between them.
Try this:
echo echo ^%a:%c%=thin^% | cmd
The first command outputs:
echo %a:fat=thin%
which is piped into a second command shell for evaluation.
:: Use perl on %var% =~ s/$old/$new/
set var=The fat cat
set old=fat
set new=thin
ECHO before=%var%
for /f "delims=" %%m in ('echo %var% ^|perl -pe "s/%old%/%new%/" ') do set var=%%m
ECHO after=%var%
Output:
before=The fat cat
after=The thin cat