I need to create a batch file that would show me a string printed after a specific string in some log file. For example: I have a log file with a line that ends with the string "Calculated number: XX". I want to create a batch file that would go to that log, find this string and print only XX part to the screen (XX is some number that changes every now and then). Any ideas what is the best way to do that? Help will be much appreciated, thanks in advance!
-
It depends strongly on the format of the string, and if anything follows the `: XX` and how many numerals can be in the `XX` – foxidrive Apr 13 '14 at 08:06
-
What do you mean by format of the string? Nothing follows _: XX_ After that in log starts a new line. It can be anything from 0 to 10 millions. – Slava Apr 13 '14 at 08:24
2 Answers
The format of the string is what comes before and after the part you are interested in - as it can matter how the line is parsed.
This code is robust and will print the number at the end of the string, if it is indeed at the end.
It uses a helper batch file called repl.bat
- download from: https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat
Place repl.bat
in the same folder as the batch file or in a folder that is on the path.
@echo off
type "file.log" | repl ".*Calculated number: (.*)" "$1" a

- 40,353
- 10
- 53
- 68
@ECHO OFF
SETLOCAL
FOR /f "delims=" %%a IN (q23040271.txt) DO (
ECHO "%%a"|FIND "Calculated number: " >NUL 2>nul
IF NOT ERRORLEVEL 1 SET "line=%%a"&GOTO found
)
ECHO target NOT found&GOTO :eof
:found
ECHO %line:~-2%
GOTO :EOF
I used a file named q23040271.txt
containing junk text and sample data for my testing.
This relies heavily on the assumption that the very first occurrence of Calculated number:
will be the required ite, and that it will be at the end of the line - no checking is done that it is actually at the end of the line.
replacing
ECHO "%%a"|FIND "Calculated number: " >NUL 2>nul
with
ECHO "%%a"|FINDSTR /e /R /c:"Calculated number: ..." >NUL 2>nul
would perform that end-of-line check (in theory - I haven't checked it) - note the three consecutive dots.
This will be agonisngly slow if there are millions of lines - unless the target string is very early in the file.
The more information you provide, the better a solution that can be devised.

- 77,302
- 8
- 62
- 84
-
`ECHO %line:~-2%` versus `can be anything from 0 to 10 millions.` Maybe better to take the last ten or twelve chars and use `for "tokens=2 delims=:"...` to get the number. (would be easier, if it were sure, that there are no more `:` in the line) – Stephan Apr 13 '14 at 09:54