在批处理文件中,我有一个字符串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
)
其他回答
更好的答案是:
set "i=hello " world"
set i|find """" >nul && echo contains || echo not_contains
是的,我们可以在String中找到subString:
echo.%data% | FINDSTR /I "POS">Nul && (SET var=POS) || (SET noVar="variable not found")
echo.%data% | FINDSTR /I "TD1">Nul && (SET var=TD1) || (SET noVar="variable not found")
GOTO %var%
:POS
echo processes inside POS
GOTO END
:TD1
echo processes inside TD1
:END
我给出这个答案可能有点晚了,但接受的答案只适用于检查“硬编码字符串”是否是搜索字符串的一部分。
对于动态搜索,你必须这样做:
SET searchString=abcd1234
SET key=cd123
CALL SET keyRemoved=%%searchString:%key%=%%
IF NOT "x%keyRemoved%"=="x%searchString%" (
ECHO Contains.
)
注意:您可以将这两个变量作为参数。
ECHO %String%| FINDSTR /C:"%Substring%" && (Instructions)
您可以将源字符串输送到findstr,并检查ERRORLEVEL的值,以查看是否找到了模式字符串。值为0表示成功,并且找到了模式。这里有一个例子:
::
: Y.CMD - Test if pattern in string
: P1 - the pattern
: P2 - the string to check
::
@echo off
echo.%2 | findstr /C:"%1" 1>nul
if errorlevel 1 (
echo. got one - pattern not found
) ELSE (
echo. got zero - found pattern
)
当在CMD.EXE中运行时,我们得到:
C:\DemoDev>y pqrs "abc def pqr 123"
got one - pattern not found
C:\DemoDev>y pqr "abc def pqr 123"
got zero - found pattern