Search code examples
batch-filevariablesfindstr

How to get all lines in a log file containing either PASSED or FAILED written into a new file using FINDSTR?


I want to find the words passed or failed in a log file and save the lines where the match succeeded in an output file. I wrote a small batch script using the findstr command. It does not seem to work.

  1. It doesn't work when I used the variables in the if exist condition which is strange.
  2. The findstr command returns nothing.

I'm a beginner in batch programming so maybe I miss-understood some notions in batch.

@echo off
set Input = simulation_results.log
set Output = sim_catchedmsg.log
if exist %Output% del %Output%
for /f "tokens=*" %%a in (%Input%) do (
  Set line=%%a 
  findstr /X "passed failed" %line% >> %Output%
  pause)   

Input log file:

<time="1500 ns" instance="testcase_00">passed
<time="342100480 ps" instance="testcase_01">passed
blabla informations about the tests....
<time="742894 ns" instance="testcase_02_01">passed
blabla informations about the tests....
blabla informations about the tests....
<time="744121040 ps" instance="testcase_02_02">failed
blabla informations about the tests....
<time="745034560 ps" instance="testcase_02_03">passed
blabla informations about the tests....
<time="745134560 ps" instance="testcase_02_04">passed
blabla informations about the tests....
blabla informations about the tests....
blabla informations about the tests....
blabla informations about the tests....
<time="745548080 ps" instance="testcase_03">failed
<time="747388640 ps" instance="testcase_04_01">passed
<time="750745100 ns" instance="testcase_04_02">passed
blabla informations about the tests....

Solution

  • You have several problems with your code.

    1) Do not put spaces on either side of the equal symbol in a SET command.

    2) You are using the FINDSTR command incorrectly. The line variable is not a file. The FINDSTR command expects the last argument to be the name of a file.

    3) You have delayed expansion problem if you really want to do the FINDSTR inside the FOR command.

    All you need to do is this.

    @echo off
    set "Input=simulation_results.log"
    set "Output=sim_catchedmsg.log"
    if exist "%Output%" del "%Output%"
    findstr "passed failed" "%input%">>"%Output%"