Set variable to result of "Find" in batch-file

66,810

Solution 1

from the command line

for /f "tokens=3" %f in ('find /c /i "Transfer Complete" "C:\ftp.LOG"') do set isComplete=%f 

from the batch script

for /f "tokens=3" %%f in ('find /c /i "Transfer Complete" "C:\ftp.LOG"') do set isComplete=%%f 

Solution 2

You don't need to use the for command; find will set the ERRORLEVEL to one of these values, based on the result:

  • 0, At least one match was found.
  • 1, no matches were found.
  • 2 or more, an error occurred.

Since it looks like you just want to see if the transfer completed, and not the total count of times the string appears, you can do something like this:

@echo OFF

@find /c /i "Transfer Complete" "C:\test path\ftp.LOG" > NUL
if %ERRORLEVEL% EQU 0 (
    @echo Success
) else (
    @echo Failure
)
Share:
66,810
MattH
Author by

MattH

Updated on July 09, 2022

Comments

  • MattH
    MattH almost 2 years

    I would like to set a variable based on the number of lines in a file that contain a give string.

    Something like:

    set isComplete = 0
    %isComplete% = find /c /i "Transfer Complete" "C:\ftp.LOG"
    IF %isComplete% > 0 ECHO "Success" ELSE ECHO "Failure"
    

    Or:

    set isComplete = 0
    find /c /i "Transfer Complete" "C:\ftp.LOG" | %isComplete%
    IF %isComplete% > 0 ECHO "Success" ELSE ECHO "Failure"
    

    Neither of those options work, obviously.

    Thanks.

  • MattH
    MattH about 15 years
    This is great. However, I should have mentioned I need this to work with a path that has a space. The quotes don't seem to help. Ugh. So... for /f "tokens=3" %%f in ('find /c /i "Transfer Complete" "C:\test path\ftp.LOG"') do set isComplete=%%f sets isComplete to "PATH\FTP.LOG:", where the error, I guess, is caused by the space.
  • Patrick Cuff
    Patrick Cuff about 15 years
    You need to use the "usebackq" option of the for command so that you can put quotes around the path: for /f "usebackq tokens=3" %%f in (find /c /i "Transfer Complete" "C:\test path\ftp.log") do set isComplete %%f
  • MattH
    MattH about 15 years
    Actually I'm now expecting a count of 2 (two files transferred) . . . so two occurrences of "Transfer Complete" = Success.
  • Patrick Cuff
    Patrick Cuff about 15 years
    The IF %isComplete% > 0 is a little confusing then; is what you really want IF %isComplete% EQU 2?