Search code examples
batch-filecmdfileparsing

Extract file string data within a time range pattern


I am trying to extract the data within a specific range of time from an input log file.

The input file, has the following pattern:

2023-01-31 00:00:21.354 FINE AS2SenderModule: Message sent and response received in 438 millisecondsms 
2023-01-31 01:00:21.352 FINE AS2SenderModule: Message sent and response received in 479 millisecondsms 
2023-01-31 09:00:23.368 FINE AS2SenderModule: Message sent and response received in 443 millisecondsms 
2023-01-31 13:00:24.857 FINE AS2SenderModule: Message sent and response received in 393 millisecondsms 
2023-01-31 14:00:26.758 FINE AS2SenderModule: Message sent and response received in 734 millisecondsms 

I have tried the following ways but all have certain issues.

set /p start_time=Enter start time (HH:MM:SS):
set /p end_time=Enter end time (HH:MM:SS):
findstr /r "%start_time%.*%end_time%" input.txt > output.txt

This didn't work, it returned an empty output file.

The other workaround, which actually works, is no good to me. It is not dynamic, requiring user input, and only works for the same range pattern. What if the user input is like 08:00:00 to 13:00:00?

for /f "tokens=11 delims= " %%a in ('findstr " 1[3-4]:[0-5][0-9]:[0-5][0-9] " input.txt ^| findstr /r /c:"millisecondsms"') do @echo %%a>> output.txt

Range can be any between 00:00:00 to 23:59:59.

Please suggest a way.


Solution

  • @ECHO OFF
    SETLOCAL
    
    :: fixed start/end times for ease of testing
    
    SET "start_time=09:00:23"
    SET "end_time=13:00:25"
    
    (
    FOR /f "usebackqtokens=1,2,*delims=. " %%g IN ("q75568748.txt") DO IF "%%h" geq "%start_time%" (
     IF "%%h" gtr "%end_time%" GOTO done
     ECHO %%g %%h.%%i
    )
    )>"u:\sel.txt"
    
    :done
    GOTO :EOF
    

    I've used fixed times and filenames that suit my system.

    It all revolves around tokenising each data line using . and Space. The portion before the first space is assigned to %%g, that between the space and dot to %%h and the remainder to %%i (see for /? from the prompt, or many articles on SO for documentation)

    Then test %%h for being greater than or equal to the start time, and then again for being greater than the end time, where a quick exit is taken if the time is after the end time.