在批处理文件中,我有一个字符串abcdefg。我想检查bcd是否在字符串中。

不幸的是,似乎所有的解决方案,我找到搜索一个文件的子字符串,而不是一个字符串的子字符串。

有没有简单的解决方法?


当前回答

ECHO %String%| FINDSTR /C:"%Substring%" && (Instructions)

其他回答

ECHO %String%| FINDSTR /C:"%Substring%" && (Instructions)

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

我通常是这样做的:

Echo.%1 | findstr /C:"%2">nul && (
    REM TRUE
) || (
    REM FALSE
)

例子:

Echo.Hello world | findstr /C:"world">nul && (
    Echo.TRUE
) || (
    Echo.FALSE
)

Echo.Hello world | findstr /C:"World">nul && (Echo.TRUE) || (Echo.FALSE)

输出:

TRUE
FALSE

我不知道这是不是最好的办法。

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

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

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正常工作。它还可以防止某些“不适当的”开头字符。