How to extract rows from a log file using Windows

2020-04-30 01:35发布

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?

6条回答
Anthone
2楼-- · 2020-04-30 01:56

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
查看更多
\"骚年 ilove
3楼-- · 2020-04-30 02:00
Get-EventLog -LogName application -EntryType warning

and export the output as you like

查看更多
在下西门庆
4楼-- · 2020-04-30 02:08

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

查看更多
叼着烟拽天下
5楼-- · 2020-04-30 02:12

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
查看更多
干净又极端
6楼-- · 2020-04-30 02:12

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.

查看更多
Deceive 欺骗
7楼-- · 2020-04-30 02:19

you can do it with PowerShell using select-stirng :

select-String  WARN  *.log 
查看更多
登录 后发表回答