gpt4 book ai didi

Powershell Convert CSV with a Column Delimited by Spaces into an array(PowerShell将带有空格分隔的列的CSV转换为数组)

转载 作者:bug小助手 更新时间:2023-10-25 17:50:45 26 4
gpt4 key购买 nike



Trying to convert a column in a non-standard CSV file into an array. I do not have an ability to change the input file since it comes from a vendor.

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


Here is the data in Test.csv:

以下是Test.csv中的数据:


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

Here is my code that works:

以下是我的代码:


$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

The above code produces the solution I want but it seems unnecessarily complex.

上面的代码产生了我想要的解决方案,但它似乎不必要地复杂。


Here is my output in Test3.csv which is what I want:

以下是我在Test3.csv中的输出,这是我想要的:


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

更多回答
优秀答案推荐

It's unclear why are you reading the file then storing an updated version of it then reading it back. You could simplify the conversion like this:

目前还不清楚为什么要先读取文件,然后存储更新版本,然后再将其读回。您可以按如下方式简化转换:


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

This could also work:

这也可以奏效:


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

更多回答

@ljg glad it was helpful

@LJG很高兴这是有帮助的

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com