Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 873
MattH Avatar asked May 06 '09 18:05

MattH


People also ask

What is @echo off in Batch Script?

When echo is turned off, the command prompt doesn't appear in the Command Prompt window. To display the command prompt again, type echo on. To prevent all commands in a batch file (including the echo off command) from displaying on the screen, on the first line of the batch file type: Copy. @echo off.

What does %% do in batch?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

Can batch file return a value?

By default when a command line execution is completed it should either return zero when execution succeeds or non-zero when execution fails. When a batch script returns a non-zero value after the execution fails, the non-zero value will indicate what is the error number.


2 Answers

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 
like image 161
Preet Sangha Avatar answered Oct 12 '22 14:10

Preet Sangha


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
)
like image 23
Patrick Cuff Avatar answered Oct 12 '22 13:10

Patrick Cuff