Search code examples
batch-filefindstrforfiles

Stop searching for a string if found while using forfiles command


I wrote a simple batch file that search for a specific string.

forfiles /S /M TraceLog-* /d +%SearchDate% /c "cmd /c findstr /c:\"Not enough disk space to save focus debug data.\" @path" >> %FileName%

Is there a way to stop the run so the output file will contain only a single message of "Not enough disk space to save focus debug data". That means - if the above string was found - stop the loop.


Solution

  • The forfiles command does not provide a feature to terminate the loop once a certain condition is fulfilled.

    However, you could instead let the loop finish but write its output to a temporary file, whose first line you copy into the target log file afterwards:

    rem // Do the loop but write output into a temporary file:
    forfiles /S /M "TraceLog-*" /D +%SearchDate% /C "cmd /D /C findstr /C:\"Not enough disk space to save focus debug data.\" @path" > "%FileName%.tmp"
    rem // Read the first line from the temporary file and store it in variable `LINE`:
    < "%FileName%.tmp" (set "LINE=" & set /P LINE="")
    rem // Append the read first line to the target log file:
    if defined LINE echo(%LINE%>> "%FileName%"
    rem // Eventually clean up the temporary file:
    del "%FileName%.tmp"
    

    This code (mis-)uses set /P intended to prompt a value from the user for reading the first line of a file in combination with input redirection <.