- 此问题在此处已有答案**:
Merging multiple CSV files into one using PowerShell(15个答案)
21天前关闭。
我有多个csv文件在一个文件夹中的数据如下
- 文件1**
"Index","Response","Status","Time"
"32190","2","Succeeded","2023-01-18 08:31:34.9"
"32189","3","Succeeded","2023-01-18 08:26:34.9"
"32188","3","Succeeded","2023-01-18 08:21:34.9"
- 文件2**
"Index","Response","Status","Time"
"32190","2","Succeeded","2023-01-19 08:31:34.9"
"32189","3","Succeeded","2023-01-19 08:26:34.9"
"32188","3","Succeeded","2023-01-19 08:21:34.9"
需要合并这些文件到一个单一的csv与一个标题
"Index","Response","Status","Time"
"32190","2","Succeeded","2023-01-18 08:31:34.9"
"32189","3","Succeeded","2023-01-18 08:26:34.9"
"32188","3","Succeeded","2023-01-18 08:21:34.9"
"32190","2","Succeeded","2023-01-19 08:31:34.9"
"32189","3","Succeeded","2023-01-19 08:26:34.9"
"32188","3","Succeeded","2023-01-19 08:21:34.9"
我有这个下面的代码,但我不能得到它的单头
$folder = 'D:\reports\daily_csv'
$files = Get-ChildItem $folder\*.csv
Get-Content $files | Set-Content "D:\Monthly\Merged_$prev_month.csv"
请让我知道我需要在这里添加什么,以避免多个标题
2条答案
按热度按时间qv7cva1a1#
这里有一种方法可以使用
StreamReader
和一个匿名函数来实现,注意.OpenText()
用UTF8编码初始化StreamReader
,如果这是一个问题,你可以使用StreamReader(String, Encoding)
来代替。drnojrws2#
Santiago Squarzon's helpful plain-text-processing answer无疑是您的最佳选择,无论是在性能方面,还是在保留格式细节方面(无论是所有字段还是仅某些字段是否使用双引号)。
一个更慢,但更方便的替代方案,不保留格式细节(不过,这应该 * 不 * 重要),是通过
-LiteralPath
参数使用Import-Csv
对 * 多个 * 输入文件的支持:注意,在PowerShell (Core) 7+中,
Export-Csv
不再需要-NoTypeInformation
或-Encoding utf8
,除非您需要不同的编码(无BOM的UTF-8现在是一致的默认值;如果确实需要BOM,请使用-Encoding utf8bom
)。另请注意,PowerShell(Core)7+中的一个错误已得到修复,可通过管道 * 将
Get-ChildItem
结果提供给Import-Csv
*: