I create batch (.bat)
script where I use findstr
with the if / else
statement.
IF
<- this is OKELSE
<- this is OKIf 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?
searchable_file.xml
:dev
current
old
stable
oldest
newest
blue
green
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.
)
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