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

前端 未结 5 1072
粉色の甜心
粉色の甜心 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条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-24 04:22

    regex is the way to go:

    $data = @'
    icon:rain
    temperatureHigh:55.37
    temperatureLow:42.55
    humidity:0.97
    windSpeed:6.7
    precipType:rain
    precipProbability:0.97
    
    icon:partly-cloudy-day
    temperatureHigh:34.75
    temperatureLow:27.1
    humidity:0.8
    windSpeed:15.32
    precipType:snow
    precipProbability:0.29
    
    icon:clear-day
    temperatureHigh:47
    temperatureLow:31.72
    humidity:0.64
    windSpeed:9.27
    precipType:rain
    precipProbability:0.01
    
    '@
    
    $head = $data
    $head = $head -replace '([^\s]+):([^\s]+)', '"$1",'
    $head = $head -replace '\n\n', '::'
    $head = $head -replace '\n', ''
    $head = $head -replace '(.*?)::.*', '$1'
    $head = $head -replace ',\s*$', ''
    $head
    
    $rows = $data
    $rows = $rows -replace '([^\s]+):([^\s]+)', '"$2",'
    $rows = $rows -replace '\n\n', '::'
    $rows = $rows -replace '\n', ''
    $rows = $rows + "::"
    $rows = $rows -replace '::', "`n"
    $rows = $rows -replace ',\s*\n', "`n"
    $rows
    

    Output:

    "icon","temperatureHigh","temperatureLow","humidity","windSpeed","precipType","precipProbability"
    "rain","55.37","42.55","0.97","6.7","rain","0.97"
    "partly-cloudy-day","34.75","27.1","0.8","15.32","snow","0.29"
    "clear-day","47","31.72","0.64","9.27","rain","0.01"
    

提交回复
热议问题