【发布时间】:2015-03-31 17:22:46
【问题描述】:
我有一个日志文件,用于监控包括请求和确认在内的大型系统。我的目标是能够:
1. 循环遍历脚本并获取请求及其确认发生的行
2. 将所有重要的行作为字符串提取,并将它们存储为变量,以便字符串修改以输出到其他地方。
这是我目前所拥有的:
@ECHO off
setlocal
setlocal enabledelayedexpansion
setlocal enableextensions
:: Lets get today's date, formatted the way the ABCD File is named
for /f "tokens=1-5 delims=/ " %%d in ("%date%") do set targetDate=%%f-%%d-%%e
:: Now we set the targetFile name
SET ABCDLogsFile=C:\Users\me\Documents\monitoring_file_for_jim\ABCDFIX*%targetDate%.log
::****Scrapped original approach*****
set "ackFoundCount=0"
set "reqFoundCount=0"
::Get lines with acks
for /f delims^=^ eol^= %%a in ('findstr /c:"\<ACK\>" "%ABCDLogsFile%"') do (
set /a "ackFoundCount+=1"
setlocal enabledelayedexpansion
for %%N in (!ackFoundCount!) do (
endlocal
set "ackFound%%N=%%a"
)
)
::Get lines with requests
for /f delims^=^ eol^= %%b in ('findstr /c:"ReqSingle" "%ABCDLogsFile%"') do (
set /a "reqFoundCount+=1"
setlocal enabledelayedexpansion
for %%N in (!reqFoundCount!) do (
endlocal
set "reqFound%%N=%%b"
)
)
setlocal enabledelayedexpansion
for /l %%N in (1,1,2 %reqFoundCount%) do echo REQ %%N FOUND= !reqFound%%N!
pause
for /l %%N in (1,1,2 %ackFoundCount%) do echo ACK %%N FOUND= !ackfound%%N!
endlocal
编辑 2 dbenham
我之前试图实现这一点的迂回方式完全没有必要。 感谢这里的问题和答案:
'findstr' with multiple search results (BATCH)
我的脚本工作类似。但是,我很好奇是否有可能在开头没有文件路径的情况下获得 findstr 输出。我只需要对日志中的时间戳进行子串化,它始终是每行的前 12 个字符(没有文件路径)。我的输出当前以路径为前缀,虽然我可以获得日志最终在生产中的路径,但尝试另一种方式会更安全。在最终运行此脚本时,每个只有 1 或 2 个请求和确认,这就是我存储所有找到的原因。没有必要,但我认为如果有两个,看到两个会让人放心。以下是acks 和reqs 类似的输出:
C:\Users\me\Documents\monitoring_file_for_jim\ABCDFIX 2015-04-01.log:2015-03-26 07:00:11,028 INFO etc...
我在想,如果我可以从一开始就去掉文件路径,那么我需要做的就是只是事件的时间戳
for /l %%N in (1,1,1 %reqFoundCount%) do echo Req %%N occurred at: !reqFound%%N:~0,12! >> MorningAckChecks.txt
for /l %%N in (1,1,1 %ackFoundCount%) do echo ACK %%N occurred at: !ackfound%%N:~0,12! >> MorningAckChecks.txt
【问题讨论】:
-
> “我试图使用带有这些变量的 for /f 作为参数来跳过和抓取这些行,但我似乎无法正确地做到这一点” - 请也发布此代码。
-
不轻易使用powershell!只需
Select-String -Pattern "stack" -List -SimpleMatch -Path F:\Andorid\Andorid.vmx | select Line,LineNumber,您就可以非常简单地获得与您的模式和行号匹配的行! -
我正在考虑使用 powershell 来执行此操作,但在建议我这样做的潜在解决方案中,没有建议我使用“powershell”。
标签: batch-file for-loop batch-processing findstr logfile