views:

236

answers:

6

I would like to extract certain rows from a log file using native Windows command line tools or batch file (.bat). Here's a sample log file:

2009-12-07 14:32:38,669 INFO  Sample log
2009-12-07 14:32:43,029 INFO  Sample log
2009-12-07 14:32:45,841 DEBUG Sample log
2009-12-07 14:32:45,841 DEBUG Sample log
2009-12-07 14:32:52,029 WARN  Sample log
2009-12-07 14:32:52,466 INFO  Sample log

How to extract and print lines which have tag "WARN"? How to do this with PowerShell?

+3  A: 

One way:

findstr WARN log.txt

More complex:

for /f "tokens=1,2,3,4* delims=, " %i in (log.txt) do @if "%l"=="WARN" echo %i %j %m

OUTPUT:
2009-12-07 14:32:52 Sample log
Mark Tolonen
I believe you should use " this way `findstr "WARN" log.txt`
PA
A: 

You can always try the original DOS "find" command, it's pretty crappy though:

c:>find " WARN " filename.log

---------- FILENAME.LOG
2009-12-07 14:32:52,029 WARN  Sample log

c:>

You can't use wildcards in the filename either.

Adrian Pronk
you can with `findstr`, though, and you got regular expressions—sort of. `find` isn't the only thing out there :-)
Joey
I never use it any more unless I'm using a bare-bones Windows machine and have no alternative. I've never heard of findstr before. That looks somewhat usable!
Adrian Pronk
+5  A: 

you can do it with PowerShell using select-stirng :

select-String  WARN  *.log 
Alon
This is the best and the right answer, but requirements often expand and sooner or later we all end up here: `gci . -r *.log | % { gc $_.fullname | ? { $_ -cmatch "WARN" }}`i.e., `get-childitem . -recurse *.log | foreach { get-content $_.fullname | ? { $_ -cmatch "WARN" }}`
Mike
A: 

there are several ways, findstr/find like what others show you. Or you can use vbscript

Set objFS=CreateObject("Scripting.FileSystemObject")
Set objArgs = WScript.Arguments
strFile= objArgs(0)
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
    strLine = objFile.ReadLine
    If InStr(strLine,"WARN") > 0 Then
        WScript.Echo strLine
    End If 
Loop

save as mygrep_warn.vbs and on command line

c:\test> cscript //nologo mygrep_warn.vbs myfile.log

Other methods, if you can download stuff and use GNU *nix tools ported to win32

C:\test>grep -i "warn" file
2009-12-07 14:32:52,029 WARN  Sample log

C:\test>gawk "BEGIN{IGNORECASE=1}/warn/" file
2009-12-07 14:32:52,029 WARN  Sample log
ghostdog74
A: 

If PowerShell (as suggested by Alon) isn't an option, maybe Logparser will fulfill for your needs: http://www.microsoft.com/downloads/details.aspx?FamilyID=890cd06b-abf8-4c25-91b2-f8d975cf8c07&displaylang=en

Filburt
A: 

Get-EventLog -LogName application -EntryType warning

and export the output as you like

Knewbyte