Search code examples
regexwindowsbatch-fileword-boundary

How to find particular pattern with regex in windows batch file?


Requirement: Parsing a text file and need to extract a particular pattern of line to another file.In the output file i need only the lines with date followed by ERROR .

Batch file code:

findstr /r "^\\d{4}-\\d{2}-\\d{2}\\s+\\d{2}:\\d{2}:\\d{2},\\d{3} \<ERROR.*" server.log > "%CD%"/test.txt
pause

Input File: Sample.log

2017-11-28 00:40:16,791 ERROR [org.jboss.weld.Bean] (ServerService Thread Pool -- 269) WELD-000019: Error destroying an instance 
2017-11-28 00:40:16,791 INFO  [stdout] (ServerService Thread Pool -- 269) [ERROR][faces context is null in context utils1]
2017-11-28 00:40:16,791 INFO  [stdout] (ServerService Thread Pool -- 269) [ERROR][faces context is null in context utils1]
2017-11-28 00:40:16,791 ERROR [org.jboss.weld.Bean] (ServerService Thread Pool -- 269) WELD-000019: Error destroying an instance
2017-11-28 00:40:16,791 INFO  [stdout] (ServerService Thread Pool -- 269) [ERROR][faces context is null in context utils1]
2017-11-28 00:40:16,791 INFO  [stdout] (ServerService Thread Pool -- 269) [ERROR][faces context is null in context utils1]

Expected Output:

2017-11-28 00:40:16,791 ERROR [org.jboss.weld.Bean] (ServerService Thread Pool -- 269) WELD-000019: Error destroying an instance 
2017-11-28 00:40:16,791 ERROR [org.jboss.weld.Bean] (ServerService Thread Pool -- 269) WELD-000019: Error destroying an instance 

But currently the code return all the content in output file. Tried word boundry \ too.


Solution

  • FINDSTR /b /r "....-..-.....:..:..,....ERROR" "%filename1%
    

    where filename1 contains your sourcefilename should accomplish the task, given findstr's restricted implementation of regex.