使用 PowerShell 读取大文件并删除回车符



>我有一个大的CSV文件,我需要清除回车符。该文件是我通过另一个程序运行的数据库的 11 GB 转储。程序在回车时窒息,所以我正在尝试这样做:

$Readcount = 1000
$CSVFile = <path>    
(Get-Content -Path $CSVFile -Raw -ReadCount $ReadCount) -replace "`r", "" | Set-Content -Path $CSVFile -Force

我想坚持使用 GC,因为它的速度高于导入 CSV,但在阅读此文件时出现错误:

获取内容:内存不足,无法继续执行程序

我的最大外壳内存通过 GPO 设置为无限制。

括号内的 Get-Content 将使整个事情首先完成,将整个文件加载到内存中。 您可以这样做,但您必须写入第二个文件。 Get-Content 通常不返回行尾,因此会添加一个换行符,然后调用带有 -nonewline 选项的 Set-Content 以不添加更多行尾。 正则表达式中的"$"表示"行尾"。 读取计数选项肯定更快。 幸运的是,-replace 将适用于 1000 个元素的数组。

$Readcount = 1000
$CSVFile = 'file.csv'  
$CSVFile2 = 'file2.csv'
Get-Content -Path $CSVFile -ReadCount $Readcount | Foreach { $_ -replace '$',"`n" } | 
Set-Content -NoNewline $CSVFile2

逐行读取文件的(可能(最快方法是使用switch -File
交换机内的每一行都将剥离其换行符。
若要追加 UNIX'n换行符并写出每一行而不添加额外的换行符,可以使用 .NET AppendAllText 方法:

$CsvFileIn  = 'X:file.csv'  
$CsvFileOut = 'X:file2.csv'  # you cannot overwrite the same file while reading it..
switch -File $CsvFileIn {
# this will create the file in UTF-8 encoding without BOM
# If you don't want that, add a third parameter [System.Text.Encoding]::Default
default { [System.IO.File]::AppendAllText($CsvFileOut, "$_`n") }
}

加速 PowerShell 解决方案的关键是避免使用 cmdlet 和管道

以下组合比基于Get-Content -ReadCount的管道解决方案快得多:

  • 使用switch -File有效地循环访问输入文件的行。

  • 使用StreamWriter实例(通过System.IO.File.CreateText()(写入输出文件。(如果需要逐行处理以降低内存使用量,则无法在单个操作中写回同一文件(。

# Create a stream writer for the output file, 
# which is created as a BOM-less UTF-8 file by default.
# NOTE: Be sure to use a *full path*, because .NET's current dir. differs from
#       PowerShell's.
$streamWriter = [IO.File]::CreateText("$pwd/Modified.csv")
# Loop over all input lines, which strips the trailing newline,
# append `n (LF), and write as-is to the output file.
switch -file $CSVFile  {
default { $streamWriter.Write($_ + "`n") }
}
# Close the stream writer.
$streamWriter.Close()

最新更新