开发者

How to extract rows from a log file using Windows command line tools or batch file?

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开发者_Python百科-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?


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


you can do it with PowerShell using select-stirng :

select-String  WARN  *.log 


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


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


Get-EventLog -LogName application -EntryType warning

and export the output as you like


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜