Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read each character of argument in a batch file

sample input in cmd:

test.bat /p 1,3,4

expected result:

1
3
4

my codes so far:

@echo off
set arg = %1
set var = %2
if (%1)==(/p) (
... need code that will read and print each character of var
)
like image 867
Blackator Avatar asked Feb 18 '23 06:02

Blackator


1 Answers

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

@echo %1%

Then

test 1,2,3

Prints:

1

Because, in this context, the comma is treated as an argument delimiter.

So you either need to enclose in quotes:

test "1,2,3"

Or use a different internal delimiter:

test 1:2:3    

Unless you want the parts to be placed in %2, %3, etc., in which case you problem is solved by a trivial use of SHIFT.

For my solution I have elected to require quotes around the group parameter, "1,2,3" (though this is easily adapted for a different delimiter by changing delims=, to specify 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 like:

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

%~2 is used to remove the quotes.

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

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

like image 60
jimhark Avatar answered Mar 14 '23 21:03

jimhark