grant
grant

Reputation: 13

parse lines of text into two variables in powershell

I have a test file that is formatted as the following:

    <IPADDRESS1> # <STRINGA>
    <IPADDRESS2> # <STRINGB>
    <IPADDRESS3> # <STRINGA;STRINGB>

Sometimes there are multiple strings separated by a ";"

What I'd like to do in PowerShell is parse this into an array for each IP / String combo and output to CSV

Desired output:

    IPAddress1,STRINGA
    IPAddress2,STRINGB
    IPAddress3,STRINGA
    IPAddress3,STRINGB

This issue I am currently having with PowerShell is I can't get the ForEach to pass the IP Address part into a new line with the secondary string when i pipe it to split:

get-content C:\file.txt | %{$_ -replace " # ",""} | %{$_ -split ";"}

The output in this example:

    IPAddress1,STRINGA
    IPAddress2,STRINGB
    IPAddress3,STRINGA
    STRINGB

note, this is missing the IP Address for the last row.

My thoughts is that I need to read each line of text into a some sort of parsing function to handle the address and the string and build an array in order to output this array to a csv.

Any help would be great, if there is an easier way to do this, please let me know. I'm limited to powershell.

Upvotes: 1

Views: 3475

Answers (2)

mjolinor
mjolinor

Reputation: 68243

using your test data (can't really tell if those <> are supposed to be part of the data or not):

$text = 
'IPADDRESS1 # STRINGA',
'IPADDRESS2 # STRINGB',
'IPADDRESS3 # STRINGA;STRINGB'

$text | foreach {
$Address,$Strings = $_.split('#').trim()
Foreach ($String in $Strings.split(';'))
 {"$Address,$String" }
}


IPADDRESS1,STRINGA
IPADDRESS2,STRINGB
IPADDRESS3,STRINGA
IPADDRESS3,STRINGB

Upvotes: 2

Frode F.
Frode F.

Reputation: 54821

Is this what you're trying to do?

Get-Content C:\file.txt | % { 
    if($_ -match '<(.*?)>\s+#\s+<(.*?)>') {
        $Matches[2] -split ';' | % { "$($Matches[1]),$_" }
    } else { Write-Host "Line '$_' doesn't match regex" }
}

IPADDRESS1,STRINGA
IPADDRESS2,STRINGB
IPADDRESS3,STRINGA
IPADDRESS3,STRINGB

Upvotes: 0

Related Questions