[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
返回列表 发帖

[文本处理] [已解决]请教批处理调用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编码

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

TOP

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

回复 2# Five66

先谢过
  1. 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""
复制代码
刚放到bat脚本文件中运行报错,连文件都没读取成功;

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

TOP

会生成新文件new_ABC.txt ,编码全部默认
  1. @echo off
  2. 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'"
  3. echo done&pause&exit /b
复制代码

TOP

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

回复 1# Ru_Evan

以下代码存为 test.bat(ansi 编码存盘即可)与源文件同目录运行,假设源文件 abc.txt(代码中文件名可自定义) 是 utf-8 编码,处理结果文件 abc.new.txt(代码中文件名可自定义)也是 utf-8 编码...
  1. @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/b
复制代码

TOP

回复 5# aloha20200628

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

TOP

回复 6# Ru_Evan

你的 powershell 版本?
再试试以下版本...
  1. @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/b
复制代码

TOP

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

TOP

回复 7# aloha20200628

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

TOP

返回列表