[英]Open a file and filter it using a regular expression
I have a large logfile and I want to extract (write to a new file) certain rows. 我的日志文件很大,我想提取某些行(写入新文件)。 The problem is I need a certain row and the row before.
问题是我需要一定的行和之前的行。 So the regex should be applied on more than one row.
因此,正则表达式应应用于多行。 Notepad++ is not able to do that and I don't want to write a script for that.
Notepad ++无法做到这一点,我也不想为此编写脚本。
I assume I can do that with Powershell and a one-liner, but I don't know where to start ... 我想我可以使用Powershell和单线来做到这一点,但我不知道从哪里开始...
The regular expression is not the problem, will be something like that ^#\\d+.*?\\n.*?Failed.*?$
正则表达式不是问题,而是类似
^#\\d+.*?\\n.*?Failed.*?$
So, how can I open a file using the Powershell, passing the regex and get the rows back that fits my expression? 因此,如何使用Powershell打开文件,传递正则表达式并返回适合我的表达式的行?
Look at Select-String
and -context
parameter: 查看
Select-String
和-context
参数:
If you only need to display the matching line and the line before, use (for a test I use my log file and my regex - the date there) 如果只需要显示匹配的行和之前的行,请使用(进行测试时,我使用日志文件和正则表达式-此处的日期)
Get-Content c:\Windows\System32\LogFiles\HTTPERR\httperr2.log |
Select-String '2011-05-13 06:16:10' -context 1,0
If you need to manipulate it further, store the result in a variable and use the properties: 如果需要进一步操作,请将结果存储在变量中并使用属性:
$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
If there are more lines that match the regex, access them with brackets: 如果还有更多与正则表达式匹配的行,请使用方括号对其进行访问:
$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.