gpt4 book ai didi

Powershell:我需要清理一组 csv 文件,在导入前必须去的 header 上方有不一致数量的垃圾行

转载 作者:行者123 更新时间:2023-12-01 23:18:56 24 4
gpt4 key购买 nike

我有一组 CSV 文件需要从中导入数据,我遇到的问题是标题行上方的垃圾行数及其内容始终不同。标题行本身是一致的,所以我可以用它来检测起点应该是什么。

我不太确定从哪里开始,文件的结构如下。

Here there be garbage.
So much garbage, between 12 and 25 lines of it.
Header1,Header2,Header3,Header4,Header5
Data1,Data2,Data3,Data4,Data5

我假设最好的方法是检查标题行的行号,然后指定起始行号的 get-content 函数是前面检查的结果。

任何指导将不胜感激。

最佳答案

如果标题行如您所说一致,您可以这样做:

$header = 'Header1,Header2,Header3,Header4,Header5'
# read the file as single multiline string
# and split on the escaped header line

$data = ((Get-Content -Path 'D:\theFile.csv' -Raw) -split [regex]::Escape($header), 2)[1] |
ConvertFrom-Csv -Header $($header -split ',')

根据您的评论,您实际上只想对这些文件进行清理,而不是从中导入数据(您的问题是“我需要导入数据”),您所要做的就是附加这行代码:

$data | Export-Csv -Path 'D:\theFile.csv' -NoTypeInformation

ConvertFrom-Csv -Header $($header -split ',') 行将数据解析为一个对象数组(重新)使用被分割掉的标题行。


文本方法(不解析数据)仍然需要写出标题行,因为通过拆分文件内容将其从结果数组中移除:

$header = 'Header1,Header2,Header3,Header4,Header5'
# read the file as single multiline string
# and split on the escaped header line

$data = ((Get-Content -Path 'D:\theFile.csv' -Raw) -split [regex]::Escape($header), 2)[1]

# rewrite the file with just the header line
$header | Set-Content -Path 'D:\theFile.csv'
# then write all data lines we captured in variable $data
$data | Add-Content -Path 'D:\theFile.csv'

关于Powershell:我需要清理一组 csv 文件,在导入前必须去的 header 上方有不一致数量的垃圾行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68383312/

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