3

I am trying to compare a string that needs to be a case-sensitive compare in a DOS batch script. I cannot figure out how to turn ON the case sensitivity in a IF statement. Here is what I am doing and it is also matching on a lower case "-f", which I am trying to avoid:

SET "ARGS=%*"
IF "%ARGS:-F=%" NEQ "%ARGS%" (
  ECHO Pro option -F was found and not allowed.
  GOTO :ERROR
)
4

4 回答 4

7

Use IF /I for simplicity ... the /I switch, if specified, means do case insensitive string compares.

SET "ARGS=%*"
IF /I "%ARGS:-F=%" NEQ "%ARGS%" (
  ECHO Pro option -F was found and not allowed.
  GOTO :ERROR
)

Additionally, it is common practice to use == instead of NEQ because the later is used for numeric comparisons.

i.e.

IF %ERRORLEVEL% EQU 0 (ECHO.Ok.)
于 2014-12-02T20:10:56.653 回答
5

Your IF statement is properly performing a case sensitive search. The problem is your expansion search and replace is corrupted, as Endoro has pointed out, and the correct form "!ARGS:-F=!" is case insensitive. While expanding ARGS, it first looks for -F, disregarding case, and replaces it with nothing.

Unfortunately, that is how search and replace works. There is no method to make it case sensitive.

You could use the following to do a case sensitive test:

echo(!ARGS!|find "-F" >nul && echo Pro option -F was found.
于 2013-06-10T21:26:41.670 回答
2

Please look at my examples and the output (call <script> -F):

@echo off &setlocal 
SET "ARGS=%*"
echo "%ARGS%"
echo "%ARGS:-F=%"

"-F"
""

your version:

@echo off &setlocal enabledelayedexpansion
SET "ARGS=%*"
echo "%ARGS%"
echo "!%ARGS%:-F=!"

"-F"
"-F="
于 2013-06-10T19:58:51.533 回答
1
IF "%args:-F=-F%"=="%args%" (ECHO no sign of -f) ELSE (echo -f detected)

Should work for you - it does for me!


Interesting result.

Here's my test routine:

@ECHO OFF
SETLOCAL
CALL :test something -f
CALL :test something -F
CALL :test -f
CALL :test -F
GOTO :eof
:test
ECHO testing %*
SET "args=%*"
IF "%args:-F=-F%"=="%args%" (ECHO no sign of -f) ELSE (echo -f detected)
GOTO :EOF

And results:

testing something -f
-f detected
testing something -F
no sign of -f
testing -f
-f detected
testing -F
no sign of -f

So - works for me. Perhaps it's version-dependent. I'm using W7/64.

于 2013-06-11T01:48:32.667 回答