Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to see if a string contains a substring using batch

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%

)
like image 625
FyreeW Avatar asked Dec 03 '15 22:12

FyreeW


2 Answers

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

like image 98
Magoo Avatar answered Nov 12 '22 21:11

Magoo


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.

like image 2
aschipfl Avatar answered Nov 12 '22 20:11

aschipfl