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

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The key point is the "!" instead of "%"; I was struggling with this but your explanation sets it clear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.