Powershell将带有空格分隔列的CSV转换为数组

dojqjjoe  于 2023-09-27  发布在  Shell
关注(0)|答案(1)|浏览(117)

尝试将非标准CSV文件中的列转换为数组。我没有能力更改输入文件,因为它来自供应商。
下面是Test.csv中的数据:

"Format","MoTeC CSV File"
"Beacon Markers","171.091 322.385 481.229 630.624 778.92"

下面是我的代码:

$dataDir = "G:\Desktop Files\Exports"

$Test1CSV = "$dataDir\MoTeC_Test1.csv" 
$Test2CSV = "$dataDir\MoTeC_Test2.csv" 
$Test3CSV = "$dataDir\MoTeC_Test3.csv" 

Clear-Content $Test1CSV,$Test2CSV,$Test3CSV

$inputCSV = "$dataDir\Test.csv"

$BM = (Import-Csv $inputCSV | Select-Object 'MoTeC CSV File' ) | select -Property @{Name='BM' ;Expression={$_.'MoTeC CSV File'.replace(' ',',')}}| export-CSV $Test1CSV -NoTypeInformation 
set-content $Test1CSV ((get-content $Test1CSV) -replace '"' )
$BM2 = (Get-Content $Test1CSV.split(","))
$BM3 = $BM2.split(',') | out-file $Test2CSV  

$i = @{ Counter = 0 } #this sets the Lap #
Import-Csv $Test2CSV | Select-Object @{ N='Lap'; E={ (++$i.Counter) }}, @{ N='BeaconMarker'; E={ $_.'BM'.split(',')} } | Export-Csv $Test3CSV -NoTypeInformation -Append

上面的代码产生了我想要的解决方案,但它似乎不必要地复杂。
下面是我在Test3.csv中的输出,这是我想要的:

"Lap","BeaconMarker"
"1","171.091"
"2","322.385"
"3","481.229"
"4","630.624"
"5","778.92"
dffbzjpn

dffbzjpn1#

目前还不清楚为什么要阅读文件,然后存储更新后的版本,然后再读回来。你可以这样简化转换:

Import-Csv Test.csv | ForEach-Object { $i = 1 } {
    foreach ($line in $_.'MoTeC CSV File' -split '\s+') {
        [pscustomobject]@{
            Lap          = ($i++)
            BeaconMarker = $line
        }
    }
} | Export-Csv MoTeC_Test3.csv -NoTypeInformation

这也可以工作:

(Import-Csv Test.csv).'MoTeC CSV File' -split '\s+' | 
    ForEach-Object { $i = 1 } {
        [pscustomobject]@{
            Lap          = ($i++)
            BeaconMarker = $_
        }
    } | Export-Csv MoTeC_Test3.csv -NoTypeInformation

相关问题