1

I'm working on a batch script which will assign a variable string and then trim it. I'm facing two issues:

  1. The variables are not assigning properly. It is taking last value from from the variable file.
  2. The variables are not assigning the first time I run the script. I need to run the script second time to see if the variables have been assigned. On third run, I can see the trim is working.

My script looks like this:

@echo off
for /f "tokens=*" %%a in ('findstr "W3SVCWINSRVRHOSTS" "C:\Data\SiebelAdmin\Commands\file.txt"') do (
for /f "tokens=2 delims==" %%b in ("%%a") do (
for %%c in (%%b) do (
echo in loop
set str=%%c
echo %%c
echo.%str%
set str=%str:~-6%
echo.%str%
)))

The output looks like this on third run:

> C:\Users\parthod\Desktop>b.bat
in loop
xsj-uvapoms72
7.2.27
7.2.27
in loop
xsj-uvapoms82
7.2.27
7.2.27
in loop
172.17.2.26
7.2.27
7.2.27
in loop
172.17.2.27
7.2.27
7.2.27
aschipfl
  • 31,767
  • 12
  • 51
  • 89
parthodas
  • 11
  • 6

1 Answers1

2

You fell into the delayed expansion trap -- try this:

@echo off
setlocal EnableDelayedExpansion
for /f "tokens=*" %%a in ('findstr "W3SVCWINSRVRHOSTS" "C:\Data\SiebelAdmin\Commands\file.txt"') do (
for /f "tokens=2 delims==" %%b in ("%%a") do (
for %%c in (%%b) do (
echo in loop
set str=%%c
echo %%c
echo.!str!
set str=!str:~-6!
echo.!str!
)))
endlocal & set str=%str%

In between the setlocal/endlocal block, delayed variable expansion is active. To actually use this feature enclose the variables by !! rather than %%.
Since setlocal sets up a new namespace for variables, the compound endlocal & set statement is required to transfer the value of str beyond the block.

Community
  • 1
  • 1
aschipfl
  • 31,767
  • 12
  • 51
  • 89