K.Mulier
K.Mulier

Reputation: 9620

Windows batch file - string comparison with wildcard

I have a file myFile.txt with a bunch of strings. I wrote the following batch file to loop through the lines, and print a line if it equals a specific string (for the sake of demo, I now choose the string foo):

    @echo off
    setlocal enableextensions enabledelayedexpansion

    for /f %%i in (myFile.txt) do (

        line=%%i
        if !line! EQU foo* (
            echo !line!
        ) 

    )

In my application, I not only need to print lines that exactly match foo, but also those lines that match fooBar, fooBarFred, fooFred, ... That's why I put a wildcard there.

But it doesn't work..

Please help.

Upvotes: 1

Views: 4613

Answers (2)

Stephan
Stephan

Reputation: 56180

findstr /b "foo" myfile.txt

/b: line should start with the string

also might be useful:

/i: ignore capitalization (find foo, Foo, fOO, ...)

See findstr /? for more options

Upvotes: 4

jeb
jeb

Reputation: 82307

There are no wildcards allowed for string compares.

You can simplify it by substring your line.
But first you should fix your code.
It must be set line=%%i not line=%%i.

@echo off
setlocal enableextensions enabledelayedexpansion

for /f "delims=" %%i in (myFile.txt) do (
    set "line=%%i"
    set "first=!line:~0,3!"
    if "!first!" EQU "foo" (
        echo(!line!
    ) 
)

Upvotes: 3

Related Questions