views:

20

answers:

3

There is a way with the IF command to include a variable in a set of values?

What I mean is:

IF %%i in (abc 123 opl) echo first set

IF %%i in (xyz 456 bnm) echo second set

A: 

You can use the for statement do do this. Here's a script which lets you run it with something like:

myprog 456

and it will output in set 2:

@setlocal enableextensions enabledelayedexpansion
@echo off
for %%a in (abc 123 opl) do (
    if "x%%a"=="x%1" echo in set 1
)
for %%a in (xyz 456 bnm) do (
    if "x%%a"=="x%1" echo in set 2
)
@endlocal
paxdiablo
I saw it works but I would like to pass the variable to the for loop from within the batch file, so I would like to put %%a=123 at the beginning of the code. The command you wrote is a " variable with modifier" ?
aemme
Then you just put something like `set xx=7` at the start of the script and use `%xx%` instead of `%1`.
paxdiablo
Many thanks. The parameter you used is a modifier of the FOR command, I tried to look for it in the windows help but i didn't find it.
aemme
I have understood now that %1 is parameter provided at the dos prompt, sorry
aemme
A: 

from the command line:

C:\Users\preet>set val=99
C:\Users\preet>for %f in (100 99 21) do @if (%f)==(%val%) echo found it %f
found it 99

In a batch file

set val=99
for %%f in (100 99 21) do @if (%%f)==(%val%) echo found it %%f
Preet Sangha
ok thanks, that is simple way I prefer
aemme
A: 

And you are also not restricted to just batch in a Windows machine. There is also vbscript (and powershell). Here's how you can check using vbscript

strVar = WScript.Arguments(0)
Set dictfirst = CreateObject("Scripting.Dictionary")
Set dictsecond = CreateObject("Scripting.Dictionary")
dictfirst.Add "abc",1
dictfirst.Add "123",1
dictfirst.Add "opl",1
dictsecond.Add "xyz",1
dictsecond.Add "456",1
dictsecond.Add "bnm",1
If dictfirst.Exists(strVar) Then
    WScript.Echo strVar & " exists in first set"
ElseIf dictsecond.Exists(strVar) Then
    WScript.Echo strVar & " exists in second set"
Else
    WScript.Echo strVar & " doesn't exists in either sets"  
End If 

usage:

C:\test>cscript //nologo test.vbs abc
abc exists in first set

C:\test>cscript //nologo test.vbs xyz
xyz exists in second set

C:\test>cscript //nologo test.vbs peter
peter doesn't exists in either sets
ghostdog74