powershell - 试图截断仅保留标题行的 csv/txt 文件
问题描述
我在一个目录中有几个 csv 和 txt 文件,其中包含数据。我需要从所有这些文件中截断数据,但在每个文件中保留标题。
解决方案
您无需读取整个文件即可捕获第一行..
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
子句的速度差不多
推荐阅读
- xcode - 无法启动与模拟器 xcode 11.4.1 和 11.3 和 11.4-beta 的服务连接
- python - 如何在 Django 中向订阅用户发送电子邮件或如何在 Django 中发送新闻信函
- python - 分配为类属性时内置函数的行为
- javascript - 手机屏幕锁定时倒计时停止计时
- vue.js - Vuejs:在子组件中声明父组件
- python - 如何在python3中序列化一个对象?
- react-native - 2020 年 ionic/cordova 与 react native
- android-studio - Android Studio 如何恢复使用服务而不是运行?
- python - 阿拉伯语 reshaper.reshape() 在 python 中无法正常工作
- graphviz - 如何在 graphviz/dotEditor 中使用现有节点标签/头标签创建新边而不复制新边