Read each argument character in a batch file

sample input in cmd:

test.bat /p 1,3,4 

Expected Result:

 1 3 4 

my codes are:

 @echo off set arg = %1 set var = %2 if (%1)==(/p) ( ... need code that will read and print each character of var ) 
+4
source share
3 answers
 @echo off if "%1"=="/p" ( :LOOP echo %2 shift set arg=%2 if defined arg goto :LOOP else exit >nul ) 
+3
source

There is a potential problem with your question. If test.bat:

 @echo %1% 

Then

 test 1,2,3 

Print

 1 

Since in this context, the comma is considered as a separator of arguments.

Thus, you need to either quote:

 test "1,2,3" 

Or use another internal delimiter:

 test 1:2:3 

If you do not want the parts to be placed in% 2,% 3, etc., then the problem will be solved by the trivial use of SHIFT .

For my decision, I decided to require quotes around the group parameter "1,2,3" (although this is easy to adapt for another separator by changing delims=, , to indicate the character you want to use).

 @echo off setlocal ENABLEDELAYEDEXPANSION ENABLEEXTENSIONS set args=%~2 if "%1"=="/p" ( :NextToken for /F "usebackq tokens=1* delims=," %%f in ('!args!') do ( echo %%f set args=%%g ) if defined args goto NextToken ) 

Call:

 readch.bat /p "1,2,3" 

%~2 used to remove quotes.

The FOR statement parses the arguments, puts the first token in %f and the rest of the line in %g .

The `goto NextToken 'line passes until there are no more tokens.

+4
source
 set params=%%~2 if (%1)==(/p) ( set params=%params:,= % ) if "%params%" NEQ "" ( call :printer %params% ) goto :eof :printer :shifting if "%%1" NEQ "" ( echo %%1 ) else ( goto :eof ) shift goto :shifting goto :eof 
+1
source

All Articles