Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing line after match "something" Powershell

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.

like image 576
A.lacorazza Avatar asked Dec 18 '22 04:12

A.lacorazza


1 Answers

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.

like image 122
Mark Wragg Avatar answered Jan 03 '23 07:01

Mark Wragg