我想创建一个执行命令的批处理文件,但在执行该命令之前,它必须查找日志以查看它是否包含以下行:
DOFWADX 2013/07/24 15:42:33 -I- DATABASE IS OK.
我正在寻找特定的文本 - “DATABASE IS OK”。问题是日志中会有此行的多个条目,最新的条目将附加到文件中。
我的问题:如何查找日志文件中包含“DATABASE IS OK”的最新/最后一条条目。此外,我们有没有办法获取日志文件更改/上次更新的时间并根据该日期和时间条目过滤“DATABASE IS OK”行(如果日志文件中存在)。
所以:
DOFWADX [date and time log file was changed/updated] -I- [look for this line >>]DATABASE IS OK.
一旦找到具有最新日期戳的这一行,我想执行一个命令,不管它现在是什么。
答案1
文件更新时间戳对您没有帮助。您需要存储上次检查(即运行批处理)的时间。以下批处理将上次检查时间存储在文件中:
@echo off
setlocal enabledelayedexpansion
:: Check parameters.
if "%~1" == "" (
echo Usage: readlog.bat example.log
exit /B 1
)
:: Read time of last check from example.log.lastcheck file, or create one.
if exist "%~1.lastcheck" (
for /F "usebackq tokens=*" %%L in ("%~1.lastcheck") do set lastcheck=%%L
) else (
set lastcheck=0
)
:: Update example.log.lastcheck file with current time.
call :getunixtime %date:~-4% %date:~-8,2% %date:~-12,2% %time:~,2% %time:~3,2% %time:~6,2%
echo %unixtime% > "%~1.lastcheck"
:: Process log.
for /F "usebackq tokens=2-7 delims=/: " %%A in (`type test.log ^| findstr /c:"DATABASE IS OK"`) do (
call :getunixtime %%A %%B %%C %%D %%E %%F
:: if an OK entry older than last check exist
if !unixtime! GTR %lastcheck% (
echo doing my stuff
goto :done
)
)
:done
exit /B 0
:: Poor man's implementation of Unix time.
:getunixtime
set "unixtime=(%1-1970)*365*24*3600 + %2*30*24*3600 + %3*24*3600 + %4*3600 + %5*60 + %6"
:: Remove leading zeros to prevent octal interpretation.
set "unixtime=%unixtime: 0= %"
set /a "unixtime=%unixtime%"
goto :eof