Quickest way to organize categorized data in a text file and convert to CSV

前端 未结 5 1074
粉色の甜心
粉色の甜心 2021-01-24 03:25

I have a text file with hundreds of rows. Data fields and values separated by a colon and one empty line separating each data set. It looks something like this...

ico         


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-24 04:09

    The simplest approach would be to split your data at 2 consecutive newlines and convert the data chunks into hashtables via ConvertFrom-StringData (you must also replace : with = for that to work). The hashtables can then be converted to custom objects and exported to a CSV.

    $data = Get-Content 'C:\path\to\input.txt' -Raw
    
    $data -replace ':', '=' -split '\r?\n\r?\n' | ForEach-Object {
        [PSCustomObject]($_ | ConvertFrom-StringData)
    } | Export-Csv 'C:\path\to\output.csv' -NoType
    

    Note that the above requires PowerShell v3 or newer. For older PowerShell versions you need to adjust the code as below:

    $data = Get-Content 'C:\path\to\input.txt' | Out-String
    
    $data -replace ':', '=' -split '\r?\n\r?\n' | ForEach-Object {
        $prop = $_ | ConvertFrom-StringData
        New-Object -Type PSObject -Property $prop
    } | Export-Csv 'C:\path\to\output.csv' -NoType
    

    If you want the fields of the CSV in a particular order you can put a Select-Object between the ForEach-Object and Export-Csv:

    ... | ForEach-Object {
        ...
    } | Select-Object icon, temperatureHigh, ... | Export-Csv ...
    

    Import-Csv expects the input data organized as one dataset per row. It cannot be used for blocks of key:value pairs like your input data has.

    ConvertTo-Csv requires the same preparation as Export-Csv in the sample code above. The only difference is that the output isn't written to a file.

提交回复
热议问题