将变量设置为批处理文件中“查找”的结果

时间:2021-06-09 23:21:31

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.

2 个解决方案

#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 

#2


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

您不需要使用for命令; find将根据结果将ERRORLEVEL设置为以下值之一:

  • 0, At least one match was found.
  • 0,找到至少一个匹配。

  • 1, no matches were found.
  • 1,未找到匹配项。

  • 2 or more, an error occurred.
  • 2或更多,发生错误。

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
)

#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 

#2


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

您不需要使用for命令; find将根据结果将ERRORLEVEL设置为以下值之一:

  • 0, At least one match was found.
  • 0,找到至少一个匹配。

  • 1, no matches were found.
  • 1,未找到匹配项。

  • 2 or more, an error occurred.
  • 2或更多,发生错误。

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
)