- 1 year ago
BATCH Check if a txt file contains a string and execute the batch
Comment
1 / 1
To check if a text file contains a specific string and execute a batch script based on the result, you can use the FINDSTR
command in a batch file. Here's an example of how you can achieve this:
batch@echo off
set "filePath=C:\path\to\your\file.txt"
set "searchString=your_string"
findstr /i "%searchString%" "%filePath%" >nul
if %errorlevel% equ 0 (
echo The file contains the search string.
rem Execute your batch script here
) else (
echo The file does not contain the search string.
rem Handle the situation when the search string is not found
)
In this example:
- Set the
filePath
variable to the path of your text file. - Set the
searchString
variable to the string you want to search for. - The
FINDSTR
command is used to search for the specified string (%searchString%
) in the file specified by%filePath%
. - The
>nul
redirects the output of theFINDSTR
command to the null device, hiding it from the console. - The
IF
statement checks the%errorlevel%
variable, which contains the exit code of the previous command. If the search string is found (errorlevel
equal to 0), it means the file contains the search string, and you can execute your batch script or perform the desired actions. If the search string is not found (errorlevel
not equal to 0), it means the file does not contain the search string, and you can handle that situation accordingly.
Adjust the filePath
and searchString
variables to match your specific file path and search string. Save the batch file with a .bat
extension and run it to check if the file contains the specified string. Based on the result, the batch script will execute the corresponding block of code.