1

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.

2
  • Have a look at this answer. Very similar stackoverflow.com/questions/28057283/… Commented Jan 22, 2015 at 21:29
  • I think that will help, I just need to find a way to convert it into my use case. Thanks Commented Jan 22, 2015 at 21:42

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

5 Comments

Nice. Didn't realize the ,<substitute> was optional on the -replace operator. All this time I've been passing in '' when I just wanted to remove text. :-)
"<" and ">" are not in the data.
Updated for new data requirements.
had to add Foreach {$_ -replace ' # ','#'} before to handle spaces, but this worked for me. Thanks!
That .trim() should have taken care of the spaces. What version are you running?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.