Reputation: 67
I am trying to pick the lines from a log file based on multi-line match. How do we achieve this with Powershell?
LogFile:
Date: 2020-05-06 2:30:33 PM
Name: ABC.txt
{text}
{text}
{text}
Date: 2020-04-08 3:30:33 PM
Name: PQR.txt
{text}
Pattern I am trying to match is:
Date:
Name:
I want to pull all the lines with this pattern. I tried the below line but it doesn't work.
get-content $log_file | select-string -pattern "(?ms)Date:.*\nName:.*" -AllMatches
Output I am looking is:
Date: 2020-05-06 2:30:33 PM
Name: ABC.txt
Date: 2020-04-08 3:30:33 PM
Name: PQR.txt
After this I want to create an array or a tabular format data(preferred) as:
Date|Name
2020-05-06 2:30:33 PM|ABC.txt
2020-04-08 3:30:33 PM|PQR.txt
Thanks for all your support!!!!
Upvotes: 2
Views: 871
Reputation: 25001
You can do the following:
Get-Content $log_file -Raw |
Select-String -Pattern '(?m)^Date:.*\r?\n\s*Name:.*' -AllMatches |
Foreach-Object { $_.Matches.Value }
You should use the -Raw
switch on Get-Content
to pass in the file contents as a single string. Otherwise it is an array of strings. Using single-line modifier (?s)
, makes .
match newline characters. Since you only want to traverse two contiguous lines, I'd opt for just matching \r
and \n
explicitly without single-line modifier. Then you can use .*
without fear of it matching beyond the current line.
Since Select-String
returns the entire string that produced a match, you will need to return the MatchInfo
object's property Matches
and its property Value
to display only the matched text.
Upvotes: 4