Batch - If find content in a logfile then write it to another logfile, otherwise do nothing

2

I have a small batch that searches a log file for Errorcodes and when found write it into another one. It creates always a new logfile, but i just want to create a new logfile when content is found.

type *.log |find /i "0x00000002" >> C:\Batch\ERRORLOG_%date%.log
type *.log |find /i "0x00000003" >> C:\Batch\ERRORLOG_%date%.log
type *.log |find /i "0x00000005" >> C:\Batch\ERRORLOG_%date%.log
type *.log |find /i "0x00000020" >> C:\Batch\ERRORLOG_%date%.log

What is the best way to do this?

batch-file
cmd
asked on Stack Overflow Oct 20, 2016 by androle

2 Answers

2

use findstr, which is a bit more flexible (i.e. can handle more than one searchstring):

type *.log |findstr /i "0x00000002 0x00000003 0x00000005 0x00000020" >logfile

see findstr/? for more options

Adapted to your comment "i just want to create a logfile if content is found":

you can delete the resulting file if it's empty at the end. If you don't want it to be even created, you have to use a for loop:

for /f "delims=" %%a in ('type *.log 2^>nul ^|findstr /i "0x00000002 0x00000003 0x00000005 0x00000020"') do echo %%a>>logfile

The trick here is, that for does only execute the code after do, if there is a finding (so no redirection happens, if there are no findings). Please note, that this method is much slower because of repetitive FileOpen and FileClose events (you don't notice it with small files, but with a big number of findings it can take some dozend seconds in comparison to just a few milliseconds)

answered on Stack Overflow Oct 20, 2016 by Stephan • edited May 23, 2017 by Community
0

You didn't answer my concerns regarding the %DATE% in the filename. So here's an alternative which takes account of that.

@ECHO OFF
FOR /F "EOL=L DELIMS=" %%A IN ('WMIC OS GET LOCALDATETIME') DO FOR %%B IN (%%A
    ) DO SET "TD=%%B"
DIR/B/A-D *.LOG^
    |FINDSTR/IRF:/ "0x0000000[235] 0x00000020">C:\BATCH\ERRORLOG_%TD:~,8%.log
answered on Stack Overflow Oct 22, 2016 by Compo

User contributions licensed under CC BY-SA 3.0