drifter213
drifter213

Reputation: 109

Change format of text

Currently I have the following:

GUID=1234
PatGUID=4567
...

But I need this format, because I have a large set of data:

GUID;PatGUID
1234;4567
...

I have large number of files like that to change format. I currently try to change the format using PowerShell, however, I am open to any method for reaching my goal.

Upvotes: 0

Views: 79

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200493

Convert the content of the file to a hashtable, create a custom object from that hashtable, then export to CSV with a custom delimiter.

$ht = Get-Content 'input.txt' |
      Out-String |
      ConvertFrom-StringData

New-Object -Type PSObject -Property $ht |
    Export-Csv 'output.csv' -Delimiter ';' -NoType

On PowerShell v3 and newer you can simplify the code by replacing Get-Content | Out-String with Get-Content -Raw and using the [PSCustomObject] type accelerator instead of New-Object.

$ht = Get-Content 'input.txt' -Raw | ConvertFrom-StringData

[PSCustomObject]$ht |
    Export-Csv 'output.csv' -Delimiter ';' -NoType

If your input data contains the same keys multiple times you need to split the data into chunks and convert each of them to an object individually:

$list = (Get-Content 'input.txt' | Out-String) -split '\r?\n(?=GUID)' |
        ForEach-Object {
            $ht = $_ | ConvertFrom-StringData
            New-Object -Type PSObject -Property $ht
        }

$list | Export-Csv 'output.csv' -Delimiter ';' -NoType

\r?\n(?=GUID) is a regular expression that uses a positive lookahead assertion ((?=...)) to split the string at newlines that are followed by the string "GUID".

Upvotes: 1

Related Questions