gpt4 book ai didi

powershell - 使用powershell替换文本文件中的扩展ascii字符

转载 作者:行者123 更新时间:2023-12-03 16:52:29 29 4
gpt4 key购买 nike

我需要将几个 csv 文件中的 16 进制 93 字符替换为 ""字符串。下面是我正在使用的代码。但它不起作用我认为它不起作用的原因是因为十六进制值大于 7F(12 月 127 日)。我尝试了其他几种方法都无济于事。任何帮助,将不胜感激。

$q1 = [String](0x93 -as [char])
Get-ChildItem ".\*.csv" -Recurse | ForEach {
(Get-Content $_ | ForEach { $_.replace($q1, '""') }) |
Set-Content $_
}

注意:附件是我的测试文件的 format-h​​ex 转储图像。第一个字符是我需要对其执行替换的字符: enter image description here

最佳答案

在 Windows PowerShell 中,读取/写入 [1] 文件时的默认字符编码是“ANSI” ,即事件系统区域设置隐含的旧版 8 位代码页。
(相比之下,PowerShell Core 默认为 UTF-8。)

例如,与美国-英语系统上的系统区域设置相关联的代码页是 1252 ,即 Windows-1252 ,其中代码点 0x93是非 ASCII 引号。

但是,一旦文本文件的内容被读入内存,在内存中,字符串的字符表示为 UTF-16LE代码单元 ,即作为 .NET [string]实例。

作为 Unicode 字符,有代码点 U+201c ,表示为 0x201c在 UTF-16LE 中。

因此 - 因为在内存中所有字符串都是 UTF-16LE 代码单元 - 您需要更换的是[char] 0x201c :

$q1 = [char] 0x201c  # “
Get-ChildItem *.csv -Recurse | ForEach-Object {
(Get-Content $_.FullName) -replace $q1, '""' | Set-Content $_.FullName
}

请注意 Set-Content也使用默认字符编码,因此重写的文件也将使用“ANSI”编码 - 使用 -Encoding如果需要,可以更改输出编码的参数。

另请注意 (...)周围 Get-Content调用,这可确保我预先将输入文件完全读入内存,从而可以写回同一管道中的同一文件。
虽然这种方法很方便,但请注意,如果在完成之前中断写回输入文件,它会承担轻微的数据丢失风险。

将“ANSI”代码点转换为 Unicode 代码点

下面显示了如何使用“ANSI”(8 位)代码点,例如 0x93可以转换为其等效的 UTF-16 代码点, 0x201c :
# Convert an array of "ANSI" code points (1 byte each) to the UTF-16
# string they represent.
# Note: In Windows PowerShell, [Text.Encoding]::Default contains
# the "ANSI" encoding set by the system locale.
$str = [Text.Encoding]::Default.GetString([byte[]] 0x93) # -> '“'

# Get the UTF-16 code points of the characters making up the string.
$codePoints = [int[]] [char[]] $str

# Format the first and only code point as a hex. number.
'0x{0:x}' -f $codePoints[0] # -> '0x201c'

[1] 用 Set-Content 写文件, 那是;使用 Out-File/ >相比之下,创建 UTF-16LE(“Unicode”)文件。 Windows PowerShell 中的 cmdlet 显示了一系列令人眼花缭乱的不同编码:请参阅 this answer .幸运的是,PowerShell Core 现在始终默认为(无 BOM)UTF-8。

关于powershell - 使用powershell替换文本文件中的扩展ascii字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52174455/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com