【问题标题】:How to replace ANSI characters with UTF-8 characters and save the document in UTF-8 format?如何用 UTF-8 字符替换 ANSI 字符并将文档保存为 UTF-8 格式?
【发布时间】:2018-02-01 16:17:15
【问题描述】:

我试过运行这个:

(Get-Content c:\example.srt).replace('æ', 'ć') | Set-Content c:\example.srt

但它只会将字符 æ 替换为 ANSI c

我还希望能够同时替换 1 个以上的字符。

【问题讨论】:

  • 这似乎是一个 XY 问题。人类什么时候想用“ć”代替“æ”?你真正想做什么?而且,哪个 ANSI 编码是源?当然,脚本运行时并不总是脚本运行器的控制台编码。

标签: powershell utf-8 ansi


【解决方案1】:

你可以这样做:

将它们替换到字符组中。将符号放入字符组中。

Get-Content c:\example.srt |% {$_ -replace "[æ\._\.*]", "ć"}

它将用ć替换æ_*

喜欢:

Get-Date -Format G | foreach {$_ -replace "[:\./]", "_"}

希望对您有所帮助。

【讨论】:

  • 谢谢,这些是我需要用 4 个 UTF-8 字符替换的 4 个 ANSI 字符:"È" 和 "Č","è" 和 "č","æ" 和 "ć",和“ð”与“đ”(前两个是大写)。现在我尝试运行这个波纹管,它替换了字符,但用另一个ANSI字符(它用“c”而不是ć替换了“æ”,同样的事情适用于其他字符,它分配另一个“等效” ASCI 字符而不是 UTF-8 字符..:(Get-Content c:\example.srt) |% {$_ -replace "È", "Č"} | Set-Content c:\example.srt
  • 其实可以在notepad++中改变编码类型
  • 我试过了,但它不能正确显示/更改这些字符。到目前为止,唯一的方法是在 Windows 记事本中手动进行字符替换,但您可以想象这会很麻烦。难道我只需要在 powershell 的某个地方启用 UTF-8 支持?
  • 您使用不当...我更新了示例以包含您的路径
【解决方案2】:

你可以试一试。它将文件从Windows-1252 转换为UTF-8

$ansi = [System.Text.Encoding]::GetEncoding(1252)

Get-Content -Encoding $ansi "c:\example.srt" | Out-File -Encoding UTF-8 "c:\example.srt"

【讨论】:

  • 谢谢,这就是我得到的:Get-Content : Cannot bind argument to parameter 'Path' because it is null.
  • (我在跑:Get-Content -Encoding $ansi $example.srt | Out-File -Encoding UTF-8 $example.srt
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-22
  • 1970-01-01
  • 2010-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-08
相关资源
最近更新 更多