您提到您要添加新行above标头,这意味着不需要 CSV 特定的处理 -听起来你是在问如何前置行到现有的文本文件(恰好包含 CSV - 请注意生成的文件将不再是有效的 CSV 文件).
例如,假设目标文件名为some.csv
:
Note: 最好做一个backup在尝试这些命令之前先查看目标文件。
如果输入文件足够小以适合整个内存:
将整个目标文件作为单个字符串读入内存Get-Content -Raw
允许一个方便而简洁的解决方案:
Set-Content -LiteralPath some.csv -NoNewLine -Value (
@'
New line 1 above header
New line 2 above header
'@ + (Get-Content -Raw some.csv)
)
注意Set-Content
应用默认字符编码(活动 ANSI 代码页Windows PowerShell, PowerShell 中无 BOM 的 UTF-8Core),无论当前的编码如何some.csv
,所以你可能必须使用-Encoding
参数显式指定编码。
另请注意,这里的单引号字符串 (@'<newline>...<newline>'@
)使用与封闭脚本相同的换行符样式(CRLF(Windows 样式)与 LF(Unix 样式)),这可能与中使用的样式不匹配some.csv
- 尽管 PowerShell 本身处理具有混合换行符样式的文件没有问题。
如果文件太大而无法放入内存,请使用流式(逐行)方法:
$ErrorActionPreference = 'Stop'
# Create a temporary file and fill it with the 2 new lines.
$tempFile = [IO.Path]::GetTempFileName()
'New line 1 above header', 'New line 2 above header' | Set-Content $tempFile
# Then append the CSV file's lines one by one.
Get-Content some.csv | Add-Content $tempFile
# If that succeeded, replace the original file.
Move-Item -Force $tempFile some.csv
注意:使用Get-Content
, Set-Content
and Add-Content
cmdlet 是方便的, but slow;下一节展示了更快的替代方案。
如果性能很重要,请使用 .NET 类型,例如[IO.File]
反而:
$ErrorActionPreference = 'Stop'
# Create a temporary file...
$tempFile = [IO.Path]::GetTempFileName()
# ... and fill it with the 2 new lines.
$streamWriter = [IO.File]::CreateText($tempFile)
foreach ($lineToPrepend in 'New line 1 above header', 'New line 2 above header') {
$streamWriter.WriteLine($lineToPrepend)
}
# Then append the CSV file's lines one by one.
foreach ($csvLine in [IO.File]::ReadLines((Convert-Path some.csv))) {
$streamWriter.WriteLine($csvLine)
}
$streamWriter.Dispose()
# If that succeeded, replace the original file.
Move-Item -Force $tempFile some.csv