在批处理文件中,我有一个字符串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 STRING=F00BAH
SET SUBSTRING=F00
ECHO %STRING% | FINDSTR /C:"%SUBSTRING%" >nul & IF ERRORLEVEL 1 (ECHO CASE TRUE) else (ECHO CASE FALSE)

这对于将windows命令的输出放到布尔变量中非常有用。只需将echo替换为您想要运行的命令。您还可以使用管道将Findstr串在一起以进一步限定语句。例如,用于业务控制(SC.exe)

SC QUERY WUAUSERV | findstr /C:"STATE" | FINDSTR /C:"RUNNING" & IF ERRORLEVEL 1 (ECHO case True) else (ECHO CASE FALSE)

这一个评估SC查询输出的windows更新服务作为一个多行文本,找到包含“状态”的行,然后发现单词“running”是否出现在该行,并相应地设置错误级别。

是的,你可以使用替换并检查原始字符串:

if not x%str1:bcd=%==x%str1% echo It contains bcd

%str1:bcd=%位将str1中的bcd替换为空字符串,使其与原始字符串不同。

如果原始版本中不包含bcd字符串,那么修改后的版本将是相同的。

使用下面的脚本进行测试将显示它的运行情况:

@setlocal enableextensions enabledelayedexpansion
@echo off
set str1=%1
if not x%str1:bcd=%==x%str1% echo It contains bcd
endlocal

以及各种运行的结果:

c:\testarea> testprog hello

c:\testarea> testprog abcdef
It contains bcd

c:\testarea> testprog bcd
It contains bcd

几点注意事项:

if语句是这个解决方案的核心,其他的都是支持的东西。 等式两边前面的x是为了确保字符串bcd正常工作。它还可以防止某些“不适当的”开头字符。

在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:使用字符串作为文字搜索字符串

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

建立在@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
)