首页 > 解决方案 > Powershell:我需要清理一组 csv 文件,在导入之前必须经过的标题上方的垃圾行数不一致

问题描述

我有一组 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 函数是前面检查的结果。

任何指导将不胜感激。

标签: powershellcsv

解决方案


如果标题行与您所说的一致,则可以执行以下操作:

$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 ',')使用拆分删除的标题行将数据解析为对象数组(重新)。


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

$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'

推荐阅读