powershell - 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 ',')
使用拆分删除的标题行将数据解析为对象数组(重新)。
纯文本方法(不解析数据)仍然需要写出标题行,因为通过拆分 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'
推荐阅读
- javascript - 将 javascript 选项选择返回值分配给 angularjs 参数
- documentation - 是否有任何 PHP 库可以为 Joomla 组件、模块和插件自动创建开发人员文档
- azure-functions - Azure 函数执行能否确定其自己的传出/外部 IP 地址?
- javascript - 如何在特定页面出现后运行篡改猴子脚本?
- xamarin - Prism with Xamarin for Android - InvalidOperationException on Launch
- login - Fosuserebundle:管理员创建用户。注册后不想登录
- python - 从 txt 文件绘制底图等高线
- web-scraping - 使用 Google 表格抓取 Instagram 关注者时被阻止
- python - django 模型中的 OneToManyRelationship
- xmlhttprequest - REST 服务令牌的身份验证标头