powershell - 如何使用PowerShell在大的二进制文件中查找和替换?

标签 powershell replace binary

我有大于50 GB的二进制文件,其中包含一个特定的字符串,我想用等长的全空格字符串替换。我要查找的字符串在文件的开头,例如在第一个兆字节之内。如何使用PowerShell执行此操作?

恐怕[System.IO.File]::ReadAllBytes("myfile.bin")不是解决方案,因为我不想加载整个二进制文件。我想在第一个兆字节内进行搜索和替换。

最佳答案

从C#中采用,因此可能需要一些重构:

$path = "\path\to\binary\file"

$numberOfBytesToRead = 1000000

$stringToSearch = "Hello World!"
$enc = [system.Text.Encoding]::UTF8
[Byte[]]$replacementString = $enc.GetBytes("     ");

$fileStream = [System.IO.File]::Open($path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite)

# binary reader to search for the string 
$binaryReader = New-Object System.IO.BinaryReader($fileStream)

# get the contents of the beginning of the file
[Byte[]] $byteArray = $binaryReader.ReadBytes($numberOfBytesToRead)

# look for string
$m = [Regex]::Match([Text.Encoding]::ASCII.GetString($byteArray), $stringToSearch)
if ($m.Success)
{    
    echo "Found '$stringToSearch' at position "$m.Index
}
else
{
    echo "'$stringToSearch' was not found"
}
$fileStream.Close()

# reopen to write
$fileStream = [System.IO.File]::Open($path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Write, [System.IO.FileShare]::ReadWrite)

$binaryWriter = New-Object System.IO.BinaryWriter($fileStream)

# set file position to location of the string
$binaryWriter.BaseStream.Position = $m.Index; 
$binaryWriter.Write($replacementString)

$fileStream.Close()

关于powershell - 如何使用PowerShell在大的二进制文件中查找和替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32758807/

相关文章:

powershell - 如何解决 Add-PSSnapin Microsoft.TeamFoundation.PowerShell 和 Get-TfsChildItem 错误?

powershell - 在Powershell上相当于Unix的命令

javascript - 将 <img> 替换为 <object>

regex - 捕获并执行多行代码并将结果合并到 raku

将 Ascii 码转换为二进制码

PowerShell:将 16MB CSV 导入 PowerShell 变量会创建 >600MB 的 PowerShell 内存使用量

javascript - 仅替换具有类突出显示 javascript 的子字符串

scala - 使用 Pickling 序列化到磁盘并反序列化 Scala 对象

c++ - 无法从文件中读取简单的二进制整数? (C++)

regex - powershell 拆分中的正则表达式