gritts
gritts

Reputation: 185

"SET"ing variable from other variable is not working

I may be missing something or forgotten something but when I attempt to "SET" a variable within a batch file the value of another variable from a FOR loop, it does not work.

ECHO OFF
set /p inputfile="Enter the server list name: "
for /f %%z in (%inputfile%) do (
for /f "skip=1 tokens=1,2,3 delims=," %%a in (%%z.csv) do (
    set inst=%%b
    @echo Service Name: %%a
    @echo %inst%
    @echo Description: %%b
    @echo Install Path: %%c
)
)
pause

My end goal is to replace the "\" present within the install path retrieved with "/" so that it will be compatible with a separate java app. During testing the variable "inst" comes back empty.

The syntax I am hoping to use is here: http://ss64.com/nt/syntax-replace.html

Any suggestions?

Upvotes: 0

Views: 109

Answers (2)

Trigger
Trigger

Reputation: 145

Brackets make multiple lines 1 line. Therefore you just need to move the echo's outside of the brackets so they are on a new line.

Variables are expanded when line is read. Therefore changes won't be noticed till the next line.

For multi command lines you can force expansion at execution time using !Var! syntax and turning this on with setlocal enabledelayedexpansion.

This is syntax to use to replace stuff set file=%windir:\=\\% replaces \ with \\ in %windir%

Upvotes: 1

JosefZ
JosefZ

Reputation: 30103

SET command works. What you need is Enable Delayed Expansion

Delayed Expansion will cause variables to be expanded at execution time rather than at parse time, this option is turned on with the SETLOCAL command. When delayed expansion is in effect variables may be referenced using !variable_name! (in addition to the normal %variable_name%)

ECHO OFF
SETLOCAL enableextensions enabledelayedexpansion
set /p "inputfile=Enter the server list name: "
for /f %%z in (%inputfile%) do (
  for /f "skip=1 tokens=1,2* delims=," %%a in (%%z.csv) do (
    set "inst=%%b"
    @echo Service Name: %%a
    @echo !inst! "!inst:\=/!"
    @echo Description: %%b
    @echo Install Path: %%c
)
)
pause

Upvotes: 2

Related Questions