我正在使用Powershell脚本将数据附加到一堆文件的末尾。
每个文件都是50Mb左右的CSV文件(说200万行),大约有50个文件。
我正在使用的脚本如下所示:
$MyInvocation.MyCommand.path
$files = ls *.csv
foreach($f in $files)
{
$baseName = [System.IO.Path]::GetFileNameWithoutExtension($f)
$year = $basename.substring(0,4)
Write-Host "Starting" $Basename
$r = [IO.File]::OpenText($f)
while ($r.Peek() -ge 0) {
$line = $r.ReadLine()
$line + "," + $year | Add-Content $(".\DR_" + $basename + ".CSV")
}
$r.Dispose()
}
问题是,它非常慢。通过它们大约需要12个小时。
它不是 super 复杂,所以我不希望它花费那么长时间。
我该怎么做才能加快速度?
最佳答案
逐行读取和写入文件可能会有点慢。也许您的防病毒软件也会导致速度缓慢。使用Measure-Command
查看脚本的哪些部分是较慢的部分。
作为一般建议,宁可写一些大块而不是很多小块。您可以通过在StringBuilder中存储一些内容并将其内容附加到输出文件(例如每1000个处理的行)中来实现此目的。像这样
$sb = new-object Text.StringBuilder # New String Builder for stuff
$i = 1 # Row counter
while ($r.Peek() -ge 0) {
# Add formatted stuff into the buffer
[void]$sb.Append($("{0},{1}{2}" -f $r.ReadLine(), $year, [Environment]::NewLine ) )
if(++$i % 1000 -eq 0){ # When 1000 rows are added, dump contents into file
Add-Content $(".\DR_" + $basename + ".CSV") $sb.ToString()
$sb = new-object Text.StringBuilder # Reset the StringBuilder
}
}
# Don't miss the tail of the contents
Add-Content $(".\DR_" + $basename + ".CSV") $sb.ToString()
关于powershell - 用于CSV修改的慢速Powershell脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17316786/