首页 > 解决方案 > 试图截断仅保留标题行的 csv/txt 文件

问题描述

我在一个目录中有几个 csv 和 txt 文件,其中包含数据。我需要从所有这些文件中截断数据,但在每个文件中保留标题。

标签: powershell

解决方案


您无需读取整个文件即可捕获第一行..

Get-ChildItem -Path 'D:\Test' -File | Where-Object { $_.Extension -match '\.(csv|txt)'} | ForEach-Object {
    # only read the first line using -TotalCount
    ($_ | Get-Content -TotalCount 1) | Set-Content -Path $_.FullName
}

如果顶行为空或仅包含空格,则上述内容可能会生成空文件或仅空格文件。

那么,将这些文件快速截断到顶部 NON-EMPTY 行的最佳选择可能是:

Get-ChildItem -Path 'D:\Test' -File | Where-Object { $_.Extension -match '\.(csv|txt)'} | ForEach-Object {
    $newcontent = switch -Regex -File $_.FullName {
        '\S'  { $_ ; break}  # output the first line that is not empty or whitespace-only and exit the switch
    }
    # write back to the file
    $newcontent | Set-Content -Path $_.FullName
}

PS-Filter在 Get-ChildItem 上使用 as 参数会更快,但不幸的是,过滤器只能用于 ONE 文件模式,例如“*.csv”。
如果您需要递归(也搜索子文件夹),那么您可以使用-Include接受文件模式数组的参数。但是,要使其正常工作,您还需要添加开关-Recurse或路径以\*.
-Include没有那么快-Filter,与上面示例中使用Where-Object子句的速度差不多


推荐阅读