Search code examples
batch-filefindstr

Batch file putting numbers from a findstr output into variables for IF statement?


I have a log file with the relevant parts isolated with findstr separately, like this:

   22 removed
   0 updated

The numbers change and have spaces in front of them and I'd like to get only the numbers into variables so that I could compare them to a threshold and use that as a basis whether to continue or stop the script.

SET removed_threshold=100    
SET updated_threshold=100

Basically I want the script to only continue if both of the numbers in the log file are below 100.

Problem is I'm stuck in the beginning as I can't possibly put the numbers into variables. Trying to use findstr in for /f from similar questions doesn't work, it can't find findstr nor the file even with full path.


Solution

  • My findstr comand selects only lines from the logfile which contain the keyword removed or updated preceeded by a number with at least one digit [0-9][0-9]*.

    The for /f "tokens=1,2" with the default delimiter space (ignoring leading delims) stores the number in %%A and the found keyword in %%B

    This is used for the command set "%%B_current=%%A"

    To assure the variables are actually set, they first need to be cleared and checked afterwards before the value without quotes can be compared.

    :: Q:\Test\2019\02\28\SO_54928501.cmd
    @Echo off
    SET "Logfile=.\SO_54928501.Logfile"
    
    :: clear vars
    for %%A in (removed_ updated_) do for /f "delims==" %%B in ('
        Set %%A 2^>Nul
    ') do Set "%%B="
    
    SET "removed_threshold=100"
    SET "updated_threshold=100"
    
    :: extract lines and set vars
    For /f "tokens=1,2" %%A in ('
        findstr /I "[0-9][0-9]*.removed [0-9][0-9]*.updated" ^<"%Logfile%"
    ') do set "%%B_current=%%A"
    
    if not defined removed_current (Echo removed_current not set & exit /B 1)
    if not defined updated_current (Echo updated_current not set & exit /B 2)
    if %removed_current% geq %removed_threshold% (
        Echo removed_current above treshold & exit /B 3)
    if %updated_current% geq %updated_threshold% (
        Echo updated_current above treshold & exit /B 4)
    
    Echo both values below treshold
    set removed_
    set updated_
    

    sample output with your above log data:

    > Q:\Test\2019\02\28\SO_54928501.cmd
    both values below treshold
    removed_current=22
    removed_threshold=100
    updated_current=0
    updated_threshold=100