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

标签 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 函数是前面检查的结果。

任何指导将不胜感激。

最佳答案

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

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

相关文章:

javascript - jQuery 下载带有链接 onclick 的 csv 文件

R/dplyr : Remove all rows in imported csv data frame that have NA entries only

python - 对 CSV 列进行平均

c# - 应该关闭远程 Powershell session 吗?

python - 使用 python 脚本中的嵌入式查询将 CSV 文件转储到 MySQL 数据库

linux - 如何使用 powershell 将 IP 地址解析为 Linux 主机名

powershell - 如何使用 powershell 轮询 kudu api 响应以获取部署状态

python - 从 Pandas dataFrame 中的列名称中删除 "\n"

powershell - 当目标文件夹存在或不存在时复制项目

azure - PowerShell ASR 复制组名称