我是 powershell 的新手,我正在尝试删除文件中的 NUL 字符。以下是文件快照
原始文件快照
我尝试使用下面的代码删除第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 字符,但第二行看起来像多行
转换后的文件图像
我的要求是删除 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/