powershell - 使用powershell删除文件中的NUL字符

标签 powershell powershell-2.0 powershell-3.0 powershell-4.0

我是 powershell 的新手,我正在尝试删除文件中的 NUL 字符。以下是文件快照

原始文件快照

Original file snaphsot

我尝试使用下面的代码删除第2行中的NUL字符

$filepath=<File name>
[STRING]$test = [io.file]::ReadAllText($filepath)
$test = $test -replace "\x00","`n"
$test = $test -replace "`n"," " 
echo $test
$test | out-file ./testoutput.txt

但是代码将所有记录变成单个记录。

我也尝试了下面的代码

$filepath=<filename>
$tempath=<temp file name>
Move-Item -Path $filepath -Destination $temppath
ForEach ($file in (Get-Content $temppath)) {
[STRING]$test = $file
$test = $test -replace "`0",""
$test = $test -replace "`r`n","" 
echo $test
$test | out-file $filepath -Append
}

删除了 NUL 字符,但第二行看起来像多行

转换后的文件图像

Converted file image

我的要求是删除 NUL 字符并将第二行设置为单行而不是多行。感谢对此的任何帮助

最佳答案

很难说出您想要实现的目标。看来您的文件中可能存在 NUL 字符。

如果要删除所有 NUL 字符,可以执行以下操作:

(Get-Content $filepath) -replace '\0' | Set-Content $temppath

如果您想删除仅包含 NULCRLF 的行,可以执行以下操作:

(Get-Content $filepath) -notmatch '^\0$' | Set-Content $temppath

如果要删除所有 NUL 字符以及仅包含 CRLF 或 NULCRLF 的行,可以执行以下操作:

(Get-Content $filepath) -replace '\0' -ne '' | Set-Content $temppath

如果要删除所有 NUL 字符并连接不以 | 结尾的行,可以执行以下操作:

$output = [System.Text.StringBuilder]::new()
(Get-Content $filepath) -replace "\0" | Foreach-Object {
    if ($_ -match '\|$') {
        [void]$output.AppendLine($_)
    } else {
        [void]$output.Append($_)
    }
}
$output.ToString() -replace '\r\n$' | Set-Content $temppath

关于powershell - 使用powershell删除文件中的NUL字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60786407/

相关文章:

azure - 如何在 Azure DevOps 中获取 keyvault secret 输出

powershell - Powershell检查int和double类型

tfs - 获取一组在特定日期后被修改的文件

mysql - 是否可以通过 PowerShell 连接到 MySQL DB(在 Linux 机器上),而无需任何额外的连接器/插件/等?

xml - 如何使用结构化 XML 数据编写事件日志条目?

arrays - PowerShell:修改数组的元素

powershell - 如何更新本地用户组的用户名?

powershell - 如何在 powershell 中实现输出变量?

powershell - 在Powershell中一次移动或复制多个文件

vb.net - PowerShell 无法正确识别字符串