繁体   English   中英

打开文件并使用正则表达式过滤

[英]Open a file and filter it using a regular expression

我的日志文件很大,我想提取某些行(写入新文件)。 问题是我需要一定的行和之前的行。 因此,正则表达式应应用于多行。 Notepad ++无法做到这一点,我也不想为此编写脚本。

我想我可以使用Powershell和单线来做到这一点,但我不知道从哪里开始...

正则表达式不是问题,而是类似^#\\d+.*?\\n.*?Failed.*?$

因此,如何使用Powershell打开文件,传递正则表达式并返回适合我的表达式的行?

查看Select-String-context参数:

如果只需要显示匹配的行和之前的行,请使用(进行测试时,我使用日志文件和正则表达式-此处的日期)

Get-Content c:\Windows\System32\LogFiles\HTTPERR\httperr2.log  |
    Select-String '2011-05-13 06:16:10' -context 1,0

如果需要进一步操作,请将结果存储在变量中并使用属性:

$line = Get-Content c:\Windows\System32\LogFiles\HTTPERR\httperr2.log  |
        Select-String '2011-05-13 06:16:10' -context 1

# for all the members try this:
$line | Get-Member

#line that matches the regex:
$line.Line
$line.Context.PreContext

如果还有更多与正则表达式匹配的行,请使用方括号对其进行访问:

$line = Get-Content c:\Windows\System32\LogFiles\HTTPERR\httperr2.log  |
        Select-String '2011-05-13 06:16:10' -context 1
$line[0] # first match
$line[1] # second match

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM