Blackator
Blackator

Reputation: 1561

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
)

Upvotes: 4

Views: 502

Answers (3)

jimhark
jimhark

Reputation: 5046

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.

Upvotes: 4

Bali C
Bali C

Reputation: 31221

@echo off
if "%1"=="/p" (
:LOOP
echo %2
shift
set arg=%2
if defined arg goto :LOOP else exit >nul
)

Upvotes: 3

npocmaka
npocmaka

Reputation: 57252

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

Upvotes: 1

Related Questions