在批处理文件中,我有一个字符串abcdefg。我想检查bcd是否在字符串中。
不幸的是,似乎所有的解决方案,我找到搜索一个文件的子字符串,而不是一个字符串的子字符串。
有没有简单的解决方法?
在批处理文件中,我有一个字符串abcdefg。我想检查bcd是否在字符串中。
不幸的是,似乎所有的解决方案,我找到搜索一个文件的子字符串,而不是一个字符串的子字符串。
有没有简单的解决方法?
当前回答
建立在@user839791的答案上,但我又添加了一些东西。
@echo off
rem --Set variable below--
set var=condition
rem --Uncomment below line to display contents of variable--
::echo The variable is %var%
rem --Change condition to desired string below--
ECHO.%var%| FIND /I "condition">Nul && (
rem --Occurs if the string is found--
Echo.Variable is "condition"
color C
pause
) || (
rem --Occurs if the string isn't found--
Echo.Variable is not "condition"
color A
pause
)
其他回答
在文件中搜索子字符串的解决方案也可以搜索字符串,例如。Find或findstr。 在您的情况下,最简单的解决方案是将字符串输送到命令中,而不是提供文件名等。
区分大小写的字符串: Echo "abcdefg" |查找"bcd"
忽略字符串的大小写: find /I "bcd"
如果没有找到匹配,您将在CMD上得到一个空行响应,并且%ERRORLEVEL%设置为1
ECHO %String%| FINDSTR /C:"%Substring%" && (Instructions)
我给出这个答案可能有点晚了,但接受的答案只适用于检查“硬编码字符串”是否是搜索字符串的一部分。
对于动态搜索,你必须这样做:
SET searchString=abcd1234
SET key=cd123
CALL SET keyRemoved=%%searchString:%key%=%%
IF NOT "x%keyRemoved%"=="x%searchString%" (
ECHO Contains.
)
注意:您可以将这两个变量作为参数。
在Var中查找文本,示例:
var_text="demo string test"
Echo.%var_text% | findstr /C:"test">nul && (
echo "found test"
) || Echo.%var_text% | findstr /C:"String">nul && (
echo "found String with S uppercase letter"
) || (
echo "Not Found "
)
传说:
& Execute_that和execute_this || Ex: Execute_that IF_FAIL execute this && Ex: Execute_that IF_SUCCESSFUL执行此操作 >nul命令无回显结果 中 /C:使用字符串作为文字搜索字符串
更好的答案是:
set "i=hello " world"
set i|find """" >nul && echo contains || echo not_contains