magicbennie
magicbennie

Reputation: 523

Batch - Search text file for specified string and if found set variable to 1

I can't seem to find a answer for this, all the questions seem focused on setting whats found in the text file as the variable. I just want to see if the string I have provided exists anywhere in the text file. (on its own line, not sharing a line with another string)

An example:

%usrname%= fish

%banfile%= is just a text file with NOTHING in it.

for /f "usebackq tokens=*" %%f in ('find /c /i "%usrname%" "%banfile%"') do set banned=1

Even with nothing in the text file, it still sets %banned%=1. I want it to set the variable %banned%=1 only if it finds one or more of the string "fish" inside the text file.

I am just beginning to understand the for command, so for most people this is probably going to be very simple. Thanks for any help!

Upvotes: 0

Views: 10677

Answers (2)

foxidrive
foxidrive

Reputation: 41234

To find fish on a line that has no other text, you can use this:

@echo off
set "usrname=fish"
set "banfile=c:\folder\file.txt"
set "banned="
findstr /i /r "^%usrname%$" "%banfile%" >nul && set banned=1

The /i makes it case insensitive and it will find fish on a line by itself, anywhere in the file.

Upvotes: 1

Endoro
Endoro

Reputation: 37569

you don't need a for loop for this:

find /i "%usrname%" "%banfile%" >nul 2>&1&&set /a banned=1 || set /a banned=0
echo %banned%

Upvotes: 4

Related Questions