Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if a string is in a list of strings in a DOS batch file

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

For example:

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

This would set ARG to one of the valid arguments only if it matched. Ideally case insensitively.

like image 319
justinhj Avatar asked Jun 27 '12 21:06

justinhj


People also ask

How do I search for a text string in DOS?

Using the findstr command lets you search for text within any plaintext file. Using this command within a batch file lets you search for text and create events off the results found.

What is %% in a batch file?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

How do you find if a file contains a given string using Windows command line?

Search for a text string in a file & display all the lines where it is found. "string" The text string to find (must be in quotes). [pathname] A drive/file(s) to search (wildcards accepted). /V Display all lines NOT containing the specified string. /C Count the number of lines containing the string.


1 Answers

You may also use the 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 clearer and simpler to manage with multiple options. For example, you may create the 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 this way:

if defined %1 (
   echo %1 is valid option...
   SET ARG=%1
)
like image 171
Aacini Avatar answered Sep 25 '22 13:09

Aacini