Parsing line after match "something" Powershell
You could use Select-String
and the -Context
parameter to do this:
Get-Content .\IP_info_all.txt | Select-String 'Hostname' -Context 0,1 | ForEach-Object {
$Hostname = $_.Context.PostContext
#Do something with this.. for now we'll just print out hostname
$Hostname
}
The -Context
parameter can be used to select a number of lines before/after the line that matched. If you provide a single digit input you get that number of lines before and after. By specifying two numbers you specify how many lines before and how many after (so in the example above 0 before and 1 after).
The result is returned in to a property named .Context
which has a .PostContext
sub-property containing the result of the line/s after the match.
Related videos on Youtube
A.lacorazza
Updated on September 16, 2022Comments
-
A.lacorazza over 1 year
I'm trying to parse a .txt file in order to create a .csv, the issue is that the file is too big and I don't have similar characters in all the txt, so this is a short example:
Hostname: xxx7 Network: IPv4 Address = xxxx IPv4 Netmask = xxxx IPv4 Gateway = xxxx DNS Servers = xxxx Hostname: xxxx-184 Network: IPv4 Address = xxxx IPv4 Netmask = xxxx IPv4 Gateway = xxxx DNS Servers = xxxx Hostname: xxxx-184 Network: IPv4 Address = xxxx IPv4 Netmask = xxxx IPv4 Gateway = xxxx DNS Servers = xxxx Hostname: xxxx-184
This txt file has got 500 lines. I think that if I could match one word like "hostname" i would be able to select the next line.
Something like:
$input = Get-Content C:\xxx\VNX\Audit_script\output\IP_info_all.txt $array = @() $input | foreach-object { $writeobj = $true $obj = New-Object System.Object If ($_ -match 'Hostname*') { $Hostname =
But I don't know how to select the line after Hostname.
-
Randall.Cummins over 4 yearsThanks for posting this. Do you happen to know how one might include both the context 0 AND 1 on the same line? parsing a log file that includes an error code and then more info directly under it and it would be more helpful to have something like the select-string we look for and then the postcontext value on the same line... not sure if that makes sense?
-
Mark Wragg over 4 yearsI’m not at a computer atm, but I imagine you could try using -join. E.g:
$_.context.postcontext -join ' '
. This assumes postcontext contains an array of lines. -
Randall.Cummins over 4 yearsNice! I was able to get it working. Have a great weekend.