JavaEar 专注于收集分享传播有价值的技术资料

Check whether a sub-string contains string

I am attempting to check whether a sub-string occurs within a string. If it does then I dont want to perform the 'if' conditions.

My Problem: My code that checks whether a sub-string occurs within a string is not working. It always thinks that a sub-string does NOT occur within a string when it actually does.

How can I check whether a sub-string occurs within a string in batch?

SET filePath="c:/users/abc/dir1/subdir"
SET excludeDir1="c:/users/abc/dir1"
SET excludeDir2="c:/users/abc/dir2"

REM // If the string excludeDir1 does not occur in filePath AND If the string excludeDir2 does not occur in filePath: continue
if /i NOT x%filePath:%excludeDir1%=%==x%filePath% if /i NOT x%filePath:%excludeDir2%=%==x%filePath% (
    REM // Do stuff
)

2个回答

    最佳答案
  1. You almost have it. Just remember that the parsing of the lines in a Batch file is performed from left to right, so there is no chance to nest two %variable% expansions. The way to solve it is combining one %normal% expansion and one !delayed! expansion:

    REM Next command is required in order to use Delayed !variable! Expansion
    SETLOCAL EnableDelayedExpansion
    
    SET filePath="c:/users/abc/dir1/subdir"
    SET excludeDir1="c:/users/abc/dir1"
    SET excludeDir2="c:/users/abc/dir2"
    
    REM // If the string excludeDir1 does not occur in filePath AND If the string excludeDir2 does not occur in filePath: continue
    if /i NOT "!filePath:%excludeDir1%=!" == "%filePath%" if /i NOT "!filePath:%excludeDir2%=!" == "%filePath%" (
        REM // Do stuff
    )
    
  2. 参考答案2
  3. Use powershell or install Cygwin and use a real POSIX/UNIX/LINUX shell like bash. You will have much better success testing strings and file paths with BASENAME and FILENAME and utilities like 'grep' and 'find' than what is available to you with CMD.EXE. You will also find plenty of stackoverflow examples from 10+ years ago on how to do all of that stuff in a proper shell.