Windows Batch: How to set the output of one comman

2019-08-30 00:20发布

I'm trying to parse a variable. Say NAMELIST = "AAA BBB CCC" and store each one as a variable. Then, these new variables must be used in another command. Eg:

perl.exe C:\action.pl <VAR1>
perl.exe C:\action.pl <VAR2>
perl.exe C:\action.pl <VAR3>

I'm new to Windows Batch so any help would be appreciated.

I am aware of this thread but don't fully understand the solution

Windows batch files: How to set a variable with the result of a command?

2条回答
叛逆
2楼-- · 2019-08-30 00:46

When you refer to "store each one in a variable", the involved concept here is array. You may split the words of NAMELIST variable into 3 array elements this way:

setlocal EnableDelayedExpansion
set i=0
for %%a in (%namelist%) do (
   set /A i=i+1
   set VAR!i!=%%a
)

This way, you may use each array element directly:

perl.exe C:\action.pl %VAR1%
perl.exe C:\action.pl %VAR2%
perl.exe C:\action.pl %VAR3%

Or, in a simpler way using a loop:

for /L %%i in (1,1,3) do perl.exe C:\action.pl !VAR%%i!

EDIT: You may use this method with an unlimited number of values in the NAMELIST variable, just use the previous value of %i% instead the 3 (better yet, change it by "n"). I also suggest you to use the standard array notation this way: VAR[%%i]:

setlocal EnableDelayedExpansion
set namelist=AAA BBB CCC DDD EEE FFF
set n=0
for %%a in (%namelist%) do (
   set /A n+=1
   set VAR[!n!]=%%a
)
for /L %%i in (1,1,%n%) do perl.exe C:\action.pl !VAR[%%i]!
查看更多
劫难
3楼-- · 2019-08-30 01:00

Variables in batch can be set by using for loop. I'll try to explain the example given in the link.

for /f "delims=" %%a in (command) do @set theValue=%%a

Here For /F is used to break up the output into tokens. "delims=" means no explicit separator is given so "space" is assumed. %%a is like index variable of loop however instead of traditional index variable in programming languages where index variable has a numeric value index variables in batch can store the tokens i.e. output of command. set command then sets the variable "theValue" to %%a which holds the output/token of the command. Thus if the statement is:

 for /f "delims=" %%a in (`echo Hi everyone!`) do @set theValue=%%a

theValue will then hold "Hi" as it is the first token seprated by space.

You can specify your own separator as per your requirement. Hope this helps!

查看更多
登录 后发表回答