Reputation: 1
I have a text file called NonProd.txt containing a server name on each line, i.e.
c123abc
c234abc
c345abc
cfcd123
etc.
I also have a batch file (given below) which reads each line from the text file, extracts 3 characters from each line, and holds that value in variable. I then want to use the variable to replace the XXX
characters in the mypath
variable.
The code below works in reading the text file, extracting the server names and extracting the 3 characters it needs, but I cannot get the string substitution to work, i.e. replace XXX
in mypath
with the 3 characters extracted.
Can anyone advise?
@echo off
SET mypath=C:\XXX\SYS\exe\folder\folder\
FOR /F %%X IN (NonProd.txt) DO (
echo ServerName = %%X
Call Set "SID=%%X"
Call Set "SID=%%SID:~1,3%%"
Call Echo SID = %%SID%%
ECHO mypath = %mypath%
CALL set mypath=%mypath:XXX=%SID%%
ECHO newpath = %mypath%
ECHO.
)
@echo Completed.
pause
Upvotes: 0
Views: 1542
Reputation: 2710
I didn't understand why you use call
and not enabledelayedexpansion
. Anyway, see the following code:
@echo off
cls
setlocal
(
echo c123abc
echo c234abc
echo c345abc
echo cfcd123
)>%temp%\_file.tmp
set mypath=c:\xxx\sys\exe\folder\folder\
echo:
setlocal enabledelayedexpansion
for /f "delims=" %%a in (%temp%\_file.tmp) do (
set "sid=%%a"
rem :: set "sid=!sid:~1,3!"
set mypath=%mypath:xxx=!sid:~1,3!%
echo sid: !sid!, servername: !sid:~1,3!, newpath: !mypath!
)
endlocal
echo Completed.
exit /b 0
output:
sid: c123abc, servername: 123, newpath: c:\123\sys\exe\folder\folder\
sid: c234abc, servername: 234, newpath: c:\234\sys\exe\folder\folder\
sid: c345abc, servername: 345, newpath: c:\345\sys\exe\folder\folder\
sid: cfcd123, servername: fcd, newpath: c:\fcd\sys\exe\folder\folder\
Completed.
Upvotes: 2
Reputation: 49086
The code with using delayed expansion as suggested by Aacini.
@echo off
setlocal EnableDelayedExpansion
set "mypath=C:\XXX\SYS\exe\folder\folder\"
for /F %%X IN (NonProd.txt) do (
echo ServerName = %%X
set "SID=%%X"
set "SID=!SID:~1,3!"
echo SID = !SID!
set newpath=%mypath:XXX=!SID!%
echo newpath = !newpath!
echo.
)
echo Completed.
endlocal
pause
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
for /?
if /?
set /?
setlocal /?
if /?
is included in this list although IF is not used in code as help of command IF explains delayed expansion on examples which often must be used in any block defined with (
... )
.
Upvotes: 1