返回列表 发帖

[文本处理] [已解决]请教批处理调用powershell将文件中的"\uxxxx"替换成字符

本帖最后由 Ru_Evan 于 2025-4-15 12:50 编辑

例如:
文件"ABC.txt"中含有大量格式为\uxxxx的16进制unicode字符串,请问如何在bat中调用powershell将其转换为普通字符?

bat脚本文件为utf-8编码,设置成chcp 65001模式;

"ABC.txt"文本文件也为utf-8编码

[regex]::replace((gc -raw 'ABC.txt'),'(?i)\\u([0-9a-f]{4})',{[char][int]("0x"+$args[0].groups[1])})|sc "new_ABC.txt"COPY

TOP

本帖最后由 Ru_Evan 于 2025-4-14 20:12 编辑

回复 2# Five66

先谢过
powershell -c "[regex]::replace((gc -raw 'ABC.txt'),'(?i)\\u([0-9a-f]{4})',{[char][int]("0x"+$args[0].groups[1])}) ^| sc "new_ABC.txt""COPY
刚放到bat脚本文件中运行报错,连文件都没读取成功;

对powershell完全不懂,能否帮忙以powershell -c "......"写个完整的脚本行? :handshake :handshake

TOP

会生成新文件new_ABC.txt ,编码全部默认
@echo off
powershell -c "[regex]::replace((gc -raw 'ABC.txt'),'(?i)\\u([0-9a-f]{4})',{[char][int]('0x'+$args[0].groups[1])})|sc 'new_ABC.txt'"
echo done&pause&exit /bCOPY

TOP

本帖最后由 aloha20200628 于 2025-4-14 23:55 编辑

回复 1# Ru_Evan

以下代码存为 test.bat(ansi 编码存盘即可)与源文件同目录运行,假设源文件 abc.txt(代码中文件名可自定义) 是 utf-8 编码,处理结果文件 abc.new.txt(代码中文件名可自定义)也是 utf-8 编码...
@echo off &powershell "$u2x={param($v)[char][int]($v.value.replace('\u','0x'))};$v=[regex]::replace((gc 'abc.txt' -enc utf8 -raw -readcount 1000),'(?i)\\u[\da-f]{4}',$u2x);[io.file]::writealltext('abc.new.txt',$v)" &pause&exit/bCOPY

TOP

回复 5# aloha20200628

多谢,刚才试了下,有报错,且生成了一个空白新文件;
Get-Content : 找不到与参数名称“enc”匹配的参数。
所在位置 行:1 字符: 156
+ ... 817296.txt' -enc utf8 -r ...
+                                                              ~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-Content],ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.GetContentCommandCOPY

TOP

回复 6# Ru_Evan

你的 powershell 版本?
再试试以下版本...
@echo off &powershell "$u2x={param($v)[char][int]($v.value.replace('\u','0x'))};$v=[regex]::replace([io.file]::readalltext('abc.txt'),'(?i)\\u[\da-f]{4}',$u2x);[io.file]::writealltext('abc.new.txt',$v)" &pause&exit/bCOPY

TOP

把它构造成json的样子
{"a": "\u4f60\u597d"}
然后用convertfrom-json解析出a
比较非主流😂

TOP

回复 7# aloha20200628

powershell版本是1.0的
刚刚试了,已经成功了。。再次感谢。。 :handshake :handshake

TOP

返回列表