Anthony Jack
Anthony Jack

Reputation: 53

Find a line in a log and split the text batch

I am trying to make a simple batch file that will first look for a specified line of text in a log, then separate it, then average it. I know how to average it but the finding and then separating it are what I need to know how to do. This is a mockup of the log

[20:36:33] [Client thread/INFO]: [CHAT] Some text here that I don't need
[20:36:33] [Client thread/INFO]: [CHAT] Some more text here that I don't need
[20:36:33] [Client thread/INFO]: [CHAT] Text I want $30023
[20:36:33] [Client thread/INFO]: [CHAT] More text here that I don't need
[20:36:33] [Client thread/INFO]: [CHAT] Text I want $40324

I will go on like that for a while, I what to first find the text that will say something like Text I want $ and then a number. I want to then take that number and average it with the other numbers that It said previously. The message in the log Text I want a number will appear at maximum 30 seconds apart.

Upvotes: 1

Views: 40

Answers (1)

Regejok
Regejok

Reputation: 446

setlocal
set x=0
set n=0
for /f "delims=$ tokens=2" %%# in ('findstr /r /c:"Text I want \$[0-9]*$" "log.txt"') do (echo %%#
set /a x+=%%#
set /a n+=1)
set /a x=(2*x+n)/(2*n)
echo Average: %x%

This will find "Text I want $NUBMER" in log.txt and print out the number after the "$".

EDIT: I have discovered a limitation to this - If the last line in log.txt does not have a linebreak, i.e. if the last line of the .txt isn't empty, the last line will be ignored. Piping the output of type into findstr counters this:

for /f "delims=$ tokens=2" %%# in ('type "log.txt"^|findstr /r /c:"Text I want \$[0-9]*$"') do ...

Upvotes: 1

Related Questions