How to find a line in a list of lines in a DOS batch file

I would like to check if an argument is valid for a batch file based on a list of strings.

For instance:

IF %1 IN validArgument1, validArgument2, validArgument3 SET ARG=%1

This will set ARG for one of the valid arguments only if it matches. The ideal case is insensitive.

+6
source share
2 answers

You can also use an array approach:

setlocal EnableDelayedExpansion

set arg[1]=validArgument1
set arg[2]=validArgument2
set arg[3]=validArgument3

for /L %%i in (1,1,3) do if /I "%1" equ "!arg[%%i]!" SET "ARG=!arg[%%i]!"

In my opinion, this method is more understandable and easier to manage multiple options. For example, you can create an array of valid arguments this way:

set i=0
for %%a in (validArgument1 validArgument2 validArgument3) do (
   set /A i+=1
   set arg[!i!]=%%a
)

Another possibility is to define a variable for each valid argument:

for %%a in (validArgument1 validArgument2 validArgument3) do set %%a=1

... and then just check the parameter as follows:

if defined %1 (
   echo %1 is valid option...
   SET ARG=%1
)
+3
source

A sustainable method is to use slow expansion

setlocal enableDelayedExpansion
set "validArgs=;arg1;arg2;arg3;"
if "!validArgs:;%~1;=!" neq "!validArgs!" set ARG=%1

CALL , , .

set "validArgs=;arg1;arg2;arg3;"
call set "test=%%validArgs:;%~1;=%%"
if "%test%" neq "%validArgs%" set ARG=%1

, arg =, args *.

, * ? , ; = <space>

set "validArgs=arg1;arg2;arg3"
for %%A in (%validArgs%) if /i "%~1"=="%%A" set ARG=%1

, . , .

+4

All Articles