检查子字符串是否包含字符串

时间:2013-05-22 23:54:30

标签: windows batch-file

我正在尝试检查字符串中是否出现子字符串。如果确实如此,那么我不想执行'if'条件。

我的问题:我的代码检查字符串中是否出现子字符串无法正常工作。它总是认为子字符串实际上不会出现在字符串中。

如何检查批处理字符串中是否出现子字符串?

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 个答案:

答案 0 :(得分:3)

你几乎拥有它。请记住,批处理文件中的行解析是从左到右执行的,因此没有机会嵌套两个%变量%扩展。解决它的方法是结合一个%正常%扩展和一个!延迟!扩展:

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
)

答案 1 :(得分:1)

使用powershell或安装Cygwin并使用真正的POSIX / UNIX / LINUX shell,如bash。使用BASENAME和FILENAME测试字符串和文件路径以及使用CMD.EXE可以使用的“grep”和“find”等实用程序,您将获得很多更好的成功。您还可以找到大量的10年以上的stackoverflow示例,介绍如何在适当的shell中完成所有这些工作。

相关问题