File 在Powershell中高效地向单行文件的每个部分添加字符串

File 在Powershell中高效地向单行文件的每个部分添加字符串,file,powershell,while-loop,stream,byte,File,Powershell,While Loop,Stream,Byte,我这里有一些Powershell代码,允许我在单行文本文件中的每个500个字符的部分中添加一个字符串 [system.io.stream]$stream = [system.io.File]::OpenRead($path) $number_of_sections = $stream.length / 500 $count = 0 [Byte[]] $section_bytes = New-Object byte[] 500 while($count -lt $number_of_sectio

我这里有一些Powershell代码,允许我在单行文本文件中的每个500个字符的部分中添加一个字符串

[system.io.stream]$stream = [system.io.File]::OpenRead($path)
$number_of_sections = $stream.length / 500
$count = 0
[Byte[]] $section_bytes = New-Object byte[] 500

while($count -lt $number_of_sections) {
        [Void]$stream.Read($section_bytes, 0 ,500)
        $thisLine = [System.Text.ASCIIEncoding]::ASCII.GetString($section_bytes)

        $section = $thisLine.Substring(0,500)
        $string_to_be_added += "example string" + $section
        $count++
}

[Byte[]] $get_bytes = [System.IO.File]::ReadAllBytes($string_to_be_added)
$write_bytes = [System.IO.File]::WriteAllBytes($write_path, $get_bytes)
现在,这段代码逐字节读取文本文件中的大单行。当我尝试读取和写入非常大的文件(60MB及以上)时,就会出现问题。这个脚本大约需要30分钟来执行,速度太慢,占用了大量内存

是否有其他方法或代码更新可以让我更快地处理文件,并更有效地将字符串添加到每个500字符的部分?谢谢

  • 使用并正确处理文本文件
  • 不要累积输出,立即写入
  • 如果确实需要将文本累积到变量中,以便以后使用,请使用:

    下面是一个使用regexp的示例:

    $prefix = 'example string'
    $prefixRX = $prefix.Replace('$', '$$') # escape special sequences like $& etc.
                                           # see https://msdn.microsoft.com/ewy2t5e0
    $prefix + ([IO.File]::ReadAllText('r:\1.txt') -replace '(?s).{500}', ('$&' + $prefixRX)) |
        Out-File 'r:\2.txt' -Encoding utf8
    

    while
    循环在循环外直到最后一次迭代之前不会进行任何更改,因此它不会向每个部分添加字符
    ReadAllBytes()
    将文件名作为参数,在最后一次循环迭代后,无法添加
    $string\u
    也恰好是一个有效的(500+字节)文件名。然后您有一个未定义的
    $write\u路径
    。我怀疑这需要花费很长时间,因为您从未递增
    $count
    ,所以循环从未停止,而且您实际上还没有看到它完成并注意到它不起作用?我编辑了代码以包含递增。我已经在代码上面初始化了$write_路径。我想我需要一些方法来编写字符串的每一段以及每次循环执行时的500个字符,但我不确定如何编写。
    $reader = [IO.StreamReader]::new('r:\1.txt')
    $buf = [char[]]::new(500)
    $prefix = 'example string'
    $outputSize = $reader.BaseStream.Length * (1 + $prefix.Length / 500)
    $text = [Text.StringBuilder]::new([int]$outputSize) # allocate memory
    
    while (!$reader.EndOfStream) {
        $nRead = $reader.Read($buf, 0, $buf.length)
        $text.Append($prefix) >$null
        $text.Append($buf, 0, $nRead) >$null
    }
    
    $reader.Close()
    $newText = $text.ToString()
    
    $prefix = 'example string'
    $prefixRX = $prefix.Replace('$', '$$') # escape special sequences like $& etc.
                                           # see https://msdn.microsoft.com/ewy2t5e0
    $prefix + ([IO.File]::ReadAllText('r:\1.txt') -replace '(?s).{500}', ('$&' + $prefixRX)) |
        Out-File 'r:\2.txt' -Encoding utf8