无法使用Powershell在2GB XML文件中查找和替换字符串 [英] Unable to Find and Replace a string in 2GB XML file using Powershell

查看:61
本文介绍了无法使用Powershell在2GB XML文件中查找和替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Windows PowerShell的新手.我正在尝试执行一次查找并替换字符串4次.但是,即使是简单的查找和替换操作也会抛出

I am new to Windows PowerShell. I am trying to perform a find and replace string on 4 occasions. But even a simple find and replace is throwing an

引发了类型为'System.OutOfMemoryException'的异常.

Exception of type 'System.OutOfMemoryException' was thrown.

错误.我使用了Get-content.
有没有办法在不破坏内存的情况下实现它?

error. I used Get-content.
Is there a way to achieve it without disrupting the memory?

例如将".000000000Z"替换为".732Z",其中732是运行作业的毫秒数?

e.g. Replace ".000000000Z" with ".732Z" where 732 will be the milliseconds the job is run?

PSversion:3.0

PSversion: 3.0

推荐答案

Get-Content将整个文件内容加载到要执行的RAM中.

Get-Content loads the entire file content into RAM to be acted upon.

您需要升级RAM 使用不同的方法,其中有一些.

You need to upgrade your RAM Use a deferent method and there are a few of them.

Get-Content
Get-Content -Raw
Get-Content -ReadCount
Switch -File

.Net阅读器是最佳的

The .Net reader is the most optimal

[System.IO.File]::ReadAllText()
[System.IO.File]::ReadAllLines()
[System.IO.File]::ReadLines()
[System.IO.File]::OpenText().readtoend()

System.IO.File.ReadLines()很可能是您的最佳选择,因为它返回文件的所有行,但是让您立即开始遍历这些行,这意味着它不必将全部内容存储在其中.记忆. 此处有更多详细信息: https://msdn.microsoft.com/en-us/library/dd383503.aspx

System.IO.File.ReadLines() is more than likely your best choice as it returns all the lines of a file, but lets you begin iterating over the lines immediately which means it does not have to store the entire contents in memory. More details here: https://msdn.microsoft.com/en-us/library/dd383503.aspx

Requires .NET 4.0 or higher.
foreach ($line in [System.IO.File]::ReadLines($filename)) {
    # do something with $line
}

因此,您可以执行以下操作...

So, you could do something like this...

$reader = [System.IO.File]::OpenText("my.log")
try {
    for() {
        $line = $reader.ReadLine()
        if ($line -eq $null) { break }
        # process the line
        $line
    }
}
finally {
    $reader.Close()
}

或将其简化为...

$reader = [System.IO.File]::OpenText("my.log")
while($null -ne ($line = $reader.ReadLine())) {
    $line
}

这篇关于无法使用Powershell在2GB XML文件中查找和替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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