Batch FOR loop with asterisk

I have a single line CMD TEST.CMD file:

for %%f in (%1 %2 %3 %4 %5 %6 %7 %8) DO ECHO %%f 

If I run this:

 TEST this is a test 

it correctly displays each parameter on a separate line, i.e.

 this is a test 

However, if the parameter contains an asterisk, it skips it. For instance.

 TEST this is a* test 

Results in:

 this is test 

How do I get a parameter with an asterisk to process as a regular token?

Thanks.

+3
source share
3 answers

The easiest way that works for most parameters is to pass the parameters to the "array" of variables, and then use FOR / L to loop through the array. This is best achieved with delayed expansion.

This method can handle an arbitrary number of parameters - this is not limited to 9.

 @echo off setlocal :: Transfer parameters to an "array" set arg.cnt=1 :getArgs (set arg.%arg.cnt%=%1) if defined arg.%arg.cnt% ( set /a arg.cnt+=1 shift /1 goto :getArgs ) set /a arg.cnt-=1 :: Process the "array" setlocal enableDelayedExpansion for /l %%N in (1 1 %arg.cnt%) do echo arg %%N = !arg.%%N! 
+1
source

The only way I found without knowing the parameters in advance is to echo the parameters in a for loop

 for /f %%f in ('"echo %1 && echo %2 && echo %3 && etc"') DO ECHO %%f 
0
source

You cannot print this, the asterisk is a dynamic operator that in some commands matches "1 or more characters", for example, the FOR command, the only way is to use the / F option which receives the output of the command.

See what happens if you use this:

 @Echo OFF Pushd "C:\" Call :sub abc * de :sub for %%f in (%1 %2 %3 %4 %5 %6 %7 %8) DO ECHO %%f Pause&Exit 

(FOR prints all files in the current directory)

Then you need to do ...:

 @Echo OFF Call :sub abc* de :sub FOR /F "tokens=*" %%a in ('Echo %*') DO (ECHO %%a) Pause&Exit 
0
source

All Articles