13

Currently trying to see if a string, in this case the current line of a text file, contains a substring #. I am new to batch, so I am not sure exactly how I would do something like this. Here is the code set substring = #

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

    //check substring method        

    echo %string%

)
3
  • Do not put SPACEs around the = at the set command line, because they become part of the variable name and the (string) value otherwise... Commented Dec 3, 2015 at 23:32
  • @aschipfl OK, I already took that line out anyway. Commented Dec 3, 2015 at 23:38
  • I just saw that this issue is dealt with in this answer anyway... Commented Dec 3, 2015 at 23:52

4 Answers 4

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

Batch is sensitive to spaces in a SET statement. SET FLAG = N sets a variable named "FLAGSpace" to a value of "SpaceN"

The syntax SET "var=value" (where value may be empty) is used to ensure that any stray trailing spaces are NOT included in the value assigned. set /a can safely be used "quoteless".

Sign up to request clarification or add additional context in comments.

11 Comments

I do not want to print out %%a|find "substring" >nul if errorlevel 1 (echo notfound) else (echo found), just only print the string if it does not contain #
Sorry- my crystal ball must be on the blink again. Replace notfound with %%a and lose the else clause. These commands must be within the for loop.
Alright, it works now. Is there a way to do it without it printing out the code?
First line of a batch file is normally @echo off which suppresses the code display.
@Magoo u should use findstr instead of find
|
3

As an alternative to find, you can use string substitution, like this:

@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

This approach uses delayed environment variable expansion. Type setlocal /? in command prompt to find out how to enable it, and set /? to see how it works (read variables like !string! instead of %string%) and what it means. set /? also describes the string substitution syntax.

1 Comment

See my edit: I accidently did not use delayed expansion for string although I described it...
1

I had to create a function:

Use it as:

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.
)

Remember it is not case sensitive by default. Add the word true to the end of the Call if you would like to be case sensitive such as:

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

And these Functions to the bottom of your Batch File.

: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

And remember you MUST add "SETLOCAL ENABLEDELAYEDEXPANSION" to the top of your batch file or else none of this will work properly.

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

Comments

0

Function to return "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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.