Mandar Shinde
Mandar Shinde

Reputation: 1755

Batch Scripting- Wild Cards in 'If Statements'

I am writing a Batch script wherein I need to use a wild card in an if statement to match a variable against a string. If it matches, the program will go further.

if "!_var!"=="str*" (

-- SOME COMMANDS --

)

This is the syntax I have used, but I found that it is not working out at all.

Upvotes: 3

Views: 7943

Answers (2)

Andriy M
Andriy M

Reputation: 77677

IF doesn't support pattern matching but you can extract the first three characters from the variable's value and compare it to str.

The syntax for substring extraction is this:

%variable:~offset,length%

and similarly for delayed expansion:

!variable:~offset,length!

So, in your case it would be:

IF "!_var:~0,3!" == "str" (
  ...
)

Upvotes: 2

Stephan
Stephan

Reputation: 56180

echo %var% |findstr /b "str" >nul && (
  echo yes
  some more commands
) || (
  echo no
  some more commands
)

looks for (/b= at the beginning) str, (don't write to screen >nul) , if found (&&) do something, if not found (||) do another thing.

You can also add a /i to make it case-insensitive.

Upvotes: 8

Related Questions