Reputation: 349
I am trying to create a batch script wherein when a user inputs a word, the script will search for that string entered by the user in a specific file.
I have been able to find if it exists in the file but the problem is I cannot seem to make it specific only to what the user has entered.
For my file I use a .dat extension, below is a sample content of my file.
user1
user2
user3
user4
user5
In my scenario when I the user inputs user1
the script tells me that it is valid or in the list, but when the user inputs user
or 1,2,3,4,5
it still tells me that it is valid. Is there any way to make it only specific to what the user enters?
Now I'm having a hard time on how I should do this. Below is my sample code.
@echo off
set /p word=
findstr /c:%word% test.dat > Nul
if ErrorLevel 1 (
echo.Not Valid
) else (
echo.Valid
)
pause
Upvotes: 3
Views: 105
Reputation: 15018
What you want is to use the start and end of word markers:
\<xyz Word position: beginning of word
xyz\> Word position: end of word
Basically what this means is that \<
says start from the beginning of a word; this beginning is defined as various factors like being at the start of a line, having a space or other punctuation, etc, and similarly \>
says match the end, such as the next character being the end of file or end of line, space or punctuation, etc. So, if you have a line like:
user1 user2,user3user4
\<user1\>
and \<user2\>
would match as there are word start and end points surrounding them, but \<user3\>
fails because there is a u
after user3
, which is not an end of word character, and \<user4\>
fails because there is a 3
before user4
, which is not a start of word character.
This works for me:
findstr /r /c:"\<%word%\>" test.dat > Nul
Note that the /r
flag is needed to turn on regular expressions. Also note there doesn't seem to be a flag to turn off output so you don't need to redirect to Nul
.
Upvotes: 1
Reputation: 80213
findstr /X /c:"%word%" test.dat > Nul
The /x
switch insists on an exact match.
Upvotes: 2