如何使用批处理程序判断一个字符串是否包含子字符串

12

目前正在尝试查看一个字符串,即文本文件的当前行是否包含子字符串#。我对批处理不熟悉,所以不确定该如何做这样的事情。以下是代码:set substring = #

for /f "delims=," %%a in (Text.txt) do (
    set string = %%a

    //check substring method        

    echo %string%

)

不要在set命令行中在=周围放置空格,否则它们将成为变量名和(字符串)值的一部分。 - aschipfl
@aschipfl 好的,我已经把那行代码移除了。 - FyreeW
我刚刚看到这个问题已经在这个答案中得到解决了... - aschipfl
4个回答

21
echo %%a|find "substring" >nul
if errorlevel 1 (echo notfound) else (echo found)

SET 语句对空格很敏感。 SET FLAG = N 将名为 "FLAGSpace" 的变量设置为 "SpaceN"。

使用语法 SET "var=value"(其中 value 可能为空)可确保未包含在分配的值中的任何杂散尾随空格。 可以安全地使用无引号的 set /a


我不想打印出 %%a|find "substring" >nul 如果错误级别为1,则(echo notfound)否则(echo found),仅在字符串不包含#时才打印。 - FyreeW
4
抱歉,我的水晶球可能又出问题了。请把“notfound”替换为“%%a”,并删除“else”子句。这些命令必须在“for”循环内部执行。 - Magoo
好的,现在它可以工作了。有没有一种方法可以在不打印代码的情况下完成它? - FyreeW
1
批处理文件的第一行通常是 @echo off,它会抑制代码显示。 - Magoo
@Magoo,你应该使用findstr而不是find - Behrouz.M
显示剩余4条评论

2
作为对find的替代方法,您可以使用字符串替换,如下所示:
@echo off
setlocal EnableDelayedExpansion
set "substring=#"
for /f "delims=," %%a in (Text.txt) do (
    set "string=%%a"
    if "!string:%substring%=!"=="!string!" (
        rem string with substring removed equals the original string,
        rem so it does not contain substring; therefore, output it:
        echo(!string!
    )
)
endlocal

这种方法使用延迟环境变量扩展。在命令提示符中键入setlocal /?以了解如何启用它,键入set /?以查看它的工作方式(读取变量类似于!string!而不是%string%)以及它的含义。 set /?还描述了字符串替换语法。


请查看我的编辑:我不小心没有为string使用延迟扩展,尽管我已经描述了它... - aschipfl

1
我必须创建一个函数:
使用它的方式为:
SearchText = "Why does the purple cow jump over the moon?"
SearchTerm = "Purple"
CALL:checkIfStringCotainsText "%SearchText%" "%SearchTerm%" RESULT
IF %RESULT%==true(
    ECHO Text Found!
) ELSE (
    ECHO Text NOT Found.
)

默认情况下它不区分大小写。如果您希望区分大小写,请在调用结尾添加单词“true”,例如:

SearchText = "Why does the purple cow jump over the moon?"
SearchTerm = "Purple"
CALL:checkIfStringCotainsText "%SearchText%" "%SearchTerm%" RESULT true
REM # Returns false because Purple is capitalized

将这些函数添加到批处理文件的底部。
:FUNCTIONS
@REM FUNCTIONS AREA
GOTO:EOF
EXIT /B

:checkIfStringCotainsText 
@REM # CHECKS IF A STRING CONTAINS A SUBSTRING
@REM # Returns the %3 as either set to true or false
@REM # Not case sensetive by defualt. But can be set to case sensetive buying adding true as the fourth paramater
@REM # For example: CALL:checkIfStringCotainsText "Whats up SLY Fox?"   "fox"          RESULT              true
@REM #                                                 SearchText     SearchTerm 
   true-or-false    CaseSensetive?
@Rem # Will check if "Whats up SLY Fox?"" contains the text "fox"
@REM # Then check the result with: if %RESULT%==true (Echo Text Found) Else (Text Not Found)
@REM # Remember do not add %RESULT% use only RESULT .Do not add % around RESULT when calling the function.
@REM # Only add % around RESULT when checking the result.
@REM # Make sure to add "SETLOCAL ENABLEDELAYEDEXPANSION" to the top of your Batch File! This is important!
@REM # Make sure you use quotes around SearchText and SearchTerm. For example "SearchText" not SearchText.
@REM # This is because if there is a space inside the SearchText, each space will make it look like a new parameter



SET SearchString=%~1
SET SearchTerm=%~2
@REM #Check if Case Senseitive
IF [%~4]==[true] (
    @REM if %~4 is not set to anything, treat it as the default as false
    @REM - Do nothing as FindStr is normally case sensetive
) ELSE (
    @REM Change both the text and search-term both to lowercase.
    CALL:LCase SearchString SearchString
    CALL:LCase SearchTerm SearchTerm

)
@set containsText=false
@echo DEBUG: Searching for ^|%~2^| inside ^|%~1^|
@echo "!SearchString!" | find "!SearchTerm!" > nul && if errorlevel 0 (set containsText=true)
SET %3=!containsText!
@GOTO:EOF


:LCase
:UCase
@REM Converts Text to Upper or Lower Case
@REM Brad Thone robvanderwoudeDOTcom
:: Converts to upper/lower case variable contents
:: Syntax: CALL :UCase _VAR1 _VAR2
:: Syntax: CALL :LCase _VAR1 _VAR2
:: _VAR1 = Variable NAME whose VALUE is to be converted to upper/lower case
:: _VAR2 = NAME of variable to hold the converted value
:: Note: Use variable NAMES in the CALL, not values (pass "by reference")
SET _UCase=A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
SET _LCase=a b c d e f g h i j k l m n o p q r s t u v w x y z
SET _Lib_UCase_Tmp=!%1!
IF /I "%0"==":UCase" SET _Abet=%_UCase%
IF /I "%0"==":LCase" SET _Abet=%_LCase%
FOR %%Z IN (%_Abet%) DO SET _Lib_UCase_Tmp=!_Lib_UCase_Tmp:%%Z=%%Z!
SET %2=%_Lib_UCase_Tmp%
GOTO:EOF

请记住,在批处理文件的开头必须添加"SETLOCAL ENABLEDELAYEDEXPANSION",否则这些操作都无法正常运行。

SETLOCAL ENABLEDELAYEDEXPANSION
@REM # Remember to add this to the top of your batch file.

0

编写一个函数来返回 "TRUE/FALSE"。

https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/find

@ECHO OFF
SET Str=Hello

::SET SubStr=el
SET SubStr=EL
::SET SubStr=eZ

CALL :SUBSTRINGCHECK %Str% %SubStr% RESULT
ECHO %RESULT%
PAUSE

:SUBSTRINGCHECK
SET RESULT=FALSE
SET Str=%~1
SET SubStr=%~2
CALL :reset_error
ECHO "%Str%" | FIND /i "%SubStr%" >nul
IF %ERRORLEVEL% EQU 0 (
 Set RESULT=TRUE
)
SET %3=%RESULT%
exit /b

:reset_error
exit /b 0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接