在批处理文件中,我有一个字符串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

是的,我们可以在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

为了兼容性和易用性,通常最好使用FIND来执行此操作。

还必须考虑是区分大小写匹配还是不区分大小写匹配。

78点的方法(我相信我指的是paxdiablo的帖子)只会匹配大小写敏感,所以你必须为你想要匹配的每个可能迭代的每个大小写变化单独检查。

)真痛苦!只有3个字母,这意味着要完成9个不同的测试!)

此外,很多时候匹配命令输出、循环中的变量或批处理/CMD中指针变量的值更可取。

由于这些原因,这是一个更好的替代方法:

使用方法:查找[/I] [/V] " character to Match"

[/I](不区分大小写) [/V](不能包含字符)

作为单线:

ECHO.%Variable% | FIND /I "ABC">Nul && ( Echo.Found "ABC" ) || ( Echo.Did not find "ABC" )

多行:

ECHO.%Variable%| FIND /I "ABC">Nul && ( 
  Echo.Found "ABC"
) || (
  Echo.Did not find "ABC"
)

如上所述,这对于变量中不允许字符串替换的东西非常有用:

FOR %A IN (
  "Some long string with Spaces does not contain the expected string"
  oihu AljB
  lojkAbCk
  Something_Else
 "Going to evaluate this entire string for ABC as well!"
) DO (
  ECHO.%~A| FIND /I "ABC">Nul && (
    Echo.Found "ABC" in "%A"
  ) || ( Echo.Did not find "ABC" )
)

Output From a command:

    NLTest | FIND /I "ABC">Nul && ( Echo.Found "ABC" ) || ( Echo.Did not find "ABC" )

As you can see this is the superior way to handle the check for multiple reasons.
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