Search code examples
stringwindowsshellbatch-filefindstr

How to write a batch script to loop through logfiles in directory and generate a "filename.found" if i find the string "found" in the log file?


I have a directory "D:\logs" consisting of many log files eg: HRS.log, SRM.log, KRT.log, PSM.log etc. Each of this log file may or may not have a string "found" inside them. If the log file contains the string "found", then i have to generate "fileName.found" eg: "SRM.found" file in "D:\flags"folder. i have written the following script but not able to proceed further:

@echo off
setlocal ENABLEDELAYEDEXPANSION

for  %%f IN ("D:\logs\*.log") do (
    findstr /i "found" "%%f" >NUL
    if  "!ERRORLEVEL!"=="0" (
    echo.>"D:\flags\%%f.found"
    ) 
    )
    pause 
    exit /b
)

Solution

  • @echo off
    
    for /f "delims=" %%A in (
        '2^>nul findstr /i /m "found" D:\logs\*.log'
    ) do echo( > "D:\flags\%%~nA.found"
    

    findstr /i can search in the files for the case insensitive string found and use of argument /m which allows for return of only the filepaths that contain that string. This can make it more efficient as the for /f command returns the filepaths only of interest.

    %%~nA uses a for variable modifier of n which is the filename with no extension. View for /? for more information about the modifiers available.