Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

I assume I can do that with Powershell and a one-liner, but I don't know where to start ...

The regular expression is not the problem, will be something like that ^#\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?

like image 308
stema Avatar asked Jun 27 '11 10:06

stema


1 Answers

Look at Select-String and -context parameter:

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
like image 191
stej Avatar answered Nov 04 '22 08:11

stej