解决Powershell下使用rg时经常遇到的乱码问题

解决Powershell下使用rg时经常遇到的乱码问题

💡 原文中文,约1100字,阅读约需3分钟。
📝

内容提要

文章解决PowerShell中使用rg搜索时中文乱码和文本截断的问题。作者发现rg -l结果正常但经管道输出乱码,判断为PowerShell编码问题;全局UTF-8设置会导致其他软件故障,chcp 65001也无效。关键在于[Console]::OutputEncoding默认为GB2312,将其设为UTF-8即可。在PowerShell 7配置文件中添加设置UTF-8无BOM编码的语句后,rg输出恢复正常。

🔎

延伸解读

问题根源:PowerShell 输出编码默认非 UTF-8

文章指出,rg 在 PowerShell 中输出乱码或截断,并非文件编码问题,而是 PowerShell 控制台输出编码默认使用 GB2312。当 rg 输出 UTF-8 字节序列时,PowerShell 按 GB2312 解码,导致中文乱码和截断。关键变量是 [Console]::OutputEncoding,它控制从程序输出到 PowerShell 的数据流编码。

全局 UTF-8 与 chcp 的局限性

作者尝试过启用系统全局 UTF-8 支持,虽能解决问题,但会导致其他软件故障,风险较高。执行 chcp 65001 也无效,因为该命令不改变 PowerShell 内部编码变量。这说明需要更精细的调整,而非全局或临时切换代码页。

针对性修复:仅修改 OutputEncoding

文章建议将 [Console]::OutputEncoding 设为 UTF-8 无 BOM 编码。在 PowerShell 7 中,可在配置文件 Microsoft.PowerShell_profile.ps1 添加语句:$utf8NoBom = [System.Text.Utf8Encoding]::new($false); [Console]::OutputEncoding = $utf8NoBom。这样 rg 输出恢复正常,且不影响其他软件。

❓

Q&A

为什么在PowerShell中使用rg搜索中文时会出现乱码或文本截断?

因为PowerShell的[Console]::OutputEncoding默认是GB2312,而rg输出的是UTF-8编码,导致编码不匹配,从而出现乱码或截断。

如何解决PowerShell中rg输出乱码的问题?

将[Console]::OutputEncoding设置为UTF-8。可以在PowerShell配置文件中添加:$utf8NoBom = [System.Text.Utf8Encoding]::new($false); [Console]::OutputEncoding = $utf8NoBom。

启用全局UTF-8支持(Beta版)有什么风险?

虽然可以解决乱码问题,但可能导致其他软件出现故障,因此需谨慎使用。

chcp 65001命令能解决rg乱码吗?

不能,chcp 65001对此问题无效,需要更精细地调整[Console]::OutputEncoding。

PowerShell中有哪些控制编码的变量?它们的默认值是什么?

有三个变量:[Console]::InputEncoding、[Console]::OutputEncoding和$OutputEncoding。前两个默认是GB2312;$OutputEncoding在PowerShell 5中默认是US-ASCII,在PowerShell 7中默认是UTF-8。

在PowerShell 7中如何永久设置rg输出编码?

在%USERPROFILE%\Documents\PowerShell\Microsoft.Powershell_profile.ps1文件中添加:$utf8NoBom = [System.Text.Utf8Encoding]::new($false); [Console]::OutputEncoding = $utf8NoBom。

🏷️

标签

➡️

继续阅读