获取内容的替代方法 [英] Alternative to Get-Content

查看:80
本文介绍了获取内容的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有以下代码行.

(Get-Content 'file.txt') |
  ForEach-Object {$_ -replace '"', ''} |
  Set-Content 'file.txt'

这在测试时有效,但是现在我试图在实际数据文件(13 GB)上使用它,并且使用Get-Content的过程导致Powershell消耗大量RAM,并最终消耗了所有可用RAM.机器.

This worked when testing, but now I am trying to use it on real data files (13 GB) and this process of using Get-Content is causing Powershell to consume a large amount of RAM and ultimately all of the available RAM on the machine.

是否有更好的方法可以实现相同的结果而没有相同的开销?

Is there a better way that I can achieve the same result without the same amount of overhead?

似乎我在做与最佳实践相反的事情,但是不知道还有什么比上述方法更干净/更省内存的.

Seems I am doing the opposite of best practice but not sure what else would be cleaner/ less RAM intensive than the above.

推荐答案

使用流读取文件,然后它不会将其全部放入内存中,您还可以使用流来写入输出.这应该可以很好地执行,并且可以减少内存使用量:

Use a stream to read the file, then it won't put it all into memory, you can also use a stream to write the output. This should perform pretty well, and keep memory usage down:

$file = New-Object System.IO.StreamReader -Arg "c:\test\file.txt"
$outstream = [System.IO.StreamWriter] "c:\test\out.txt"

while ($line = $file.ReadLine()) {
  $s = $line -replace '"', ''
  $outstream.WriteLine($s)
}
$file.close()
$outstream.close()

这篇关于获取内容的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆