Search code examples
windowsbatch-filecmdcommand-linefindstr

Findstr ERRORLEVEL returns wrong level if I type dot's of the same length as the search string


I create batch (.bat) script where I use findstr with the if / else statement.

The part that works well:

  • If I type a valid string that matches a line in the file to be searched, it takes me to the IF <- this is OK
  • If i type not valid string, it takes me to the ELSE<- this is OK

The part that doesn't work well:

  • If I type dot's instead of letters (of the same length), it takes me to the IF. For example, if I enter ...., the number of characters matches the string blue

  • Why? The dots don't match any string in my file, so I should go to ELSE. What is wrong with my code?


My searchable_file.xml:

dev
current
old
stable
oldest
newest
blue
green

My findstr script:

SET /P SELECTION=

FINDSTR /R /C:"^%SELECTION%$" searchable_file.xml > NUL

IF NOT ERRORLEVEL 1 (
    ECHO [OK] The value entered is valid.
) ELSE (
    ECHO [ERROR] The path entered does not exist. Try again.
)

Solution

  • The /R in FINDSTR /R /C:"^%SELECTION%$" file.txt means using REGEX (where a dot serves as a wildcard). Just removing /R is useless, as it is the standard anyway. Replace it with /L (Literal) instead.

    Of course this means, ^ for "start of line" and $ for "end of line" won't work anymore (they are REGEX), but you can add the /B (Begin of line) and /E (End of line) switches instead:

    FINDSTR /L /B /E /C:"%SELECTION%" file.txt
    

    or use the /X switch (whole line):

    FINDSTR /L /X /C:"%SELECTION%" file.txt
    

    undocumented but supported feature of findstr: you can combine switches with a single /:

    FINDSTR /LXC:"%SELECTION%" file.txt
    

    Maybe you also want to use the /i switch (Ignore capitalization) to find blue, Blue, BLUE etc.:

    FINDSTR /ILXC:"%SELECTION%" file.txt