我有这个项目,我的目标是使用批处理(.bat)文件达到以下条件。
在.log文件中搜索模式,“[YYYY-MM-DD HH:MM:SS]”(1)和“错误”(2)在一行中,然后输出总出现次数。 csv文件。
使用的代码:
@ECHO OFF
findstr /i /C:"Error" *.log | find /i /c "Error" >> Error.csv
以下是一个示例日志文件模式:
[2012-04-25 16:20:2] [INFO] [SAMPLE] Error in...
.csv文件中的预期输出
以下是预期结果:
[时间] [错误计数]
1:00-2:00 125
2:00-3:00 45
3:00-4:00 246
依此类推,直到23:00-24:00
字符串ERROR的计数应该在错误计数列下分配,取决于时间戳,计算出现次数。
非常感谢。我很感激帮助! : - )
答案 0 :(得分:0)
我几乎肯定错过了测试中的某些内容,但这应该与您正在寻找的内容相符。
@echo off
setlocal enabledelayedexpansion
cls
:: Proper regex would make this /\[\d{4}(-\d{2}){2} \d{2}(:\d{2}){2}\]/g
:: Unfortunately, findstr regex is extremely limited and so our options
:: are either a short search string or a super long string
set regex_check_1=\[[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]\]
set regex_check_2=Error
:: Search (the results of searching for regex_check_1) for regex_check_2
:: and output the results to a temp file for later processing
findstr /R /C:"%regex_check_1%" data.log|findstr /I /R /C:"%regex_check_2%">temp.txt
:: Initializes the error_count arraylike values to 0
for /L %%A in (0,1,23) do set error_count[%%A]=0
:: Searches the HH column of the timestamp and, every time a number is found,
:: increments the value of the element in the error_count arraylike
for /F "tokens=2 delims=: " %%A in (temp.txt) do (
REM convert HH to H if HH<10 to avoid number being considered octal
set /a hr_num=1%%A-100
call :arraylike_inc !hr_num!
)
:: Output the data to the CSV file
echo Time Error Count>log.csv
for /L %%A in (0,1,23) do (
set start_hour=%%A
set /a end_hour=%%A+1
echo !start_hour!:00-!end_hour!:00 !error_count[%%A]!>>log.csv
)
:: End the script here so that we don't accidentally call the function again
exit /b
:: Increments the value of error_count[hour]
:: This is a function because delayed exansion can only take us so far
:arraylike_inc
set /a error_count[%1]=!error_count[%1]!+1