草稿待审
文件编码判断不准会导致乱码或跨平台问题。本文实测 6 种方法。
一、TL;DR:按场景选命令
- 快速识别:
file --mime-encoding <file>,系统自带。 - 多字节语言(中文/日文/韩文):
enca -L none <file>。 - 纯自动检测:
uchardet <file>。 - 看原始字节:
hexdump -C <file>。 - 编辑器场景:
vim -c 'set fileencoding?' -c q <file>。
二、file:系统自带,快速识别
file --mime-encoding /etc/hostname
file -bi /tmp/test_utf8.txt
file --mime-encoding 会输出类似 utf-8、us-ascii、binary 的结果 [1]。-bi 会同时返回 MIME 类型和编码。注意:file 不会区分 UTF-8 和 UTF-8 with BOM,都会返回 utf-8;二进制文件直接标为 binary。
实测输出:
/etc/hostname:us-ascii- 含中文的
/tmp/test_utf8.txt:utf-8 - 带 BOM 的 UTF-8 文件:
utf-8
三、enca / uchardet:自动检测编码
enca -L none /tmp/test_utf8.txt
uchardet /tmp/test_utf8.txt
enca 通过语言模型识别编码,但需要显式指定语言或 -L none 才能运行 [2]。实测中不指定会直接报错退出。输出如 7bit ASCII characters 或 Universal transformation format 8 bits; UTF-8。
uchardet 是 Mozilla 移植的通用字符集检测器,无需语言参数,输出 iconv 兼容编码名 [3]。实测对 ASCII/UTF-8 识别准确,但短文本可能误判。
四、hexdump:看原始字节序列
hexdump -C /etc/hostname
hexdump -C /tmp/test_utf8.txt | head -n1
hexdump -C 以十六进制加 ASCII 形式打印文件内容 [5]。通过查看左侧十六进制列可以人工判断编码:纯 0x20-0x7E 通常是 ASCII,出现 e5 9f ba 这类两字节或三字节序列则是 UTF-8 中文字符。
实测中文字符输出:
00000000 4c 69 6e 75 78 e5 9f ba e7 a1 80 e7 9f a5 e8 af |Linux.........|
五、vim:编辑器内查看 fileencoding
vim -c 'set fileencoding?' -c q /etc/hostname
Vim 会在加载文件时自动检测编码,set fileencoding? 会返回当前缓冲区的编码 [4]。实测返回 utf-8。如果文件包含 BOM,Vim 通常仍报告为 utf-8;可以通过 :set bomb? 额外检查 BOM 标记。
六、回滚、排错与局限性
排错速查
| 现象 | 原因 | 处理 |
|---|---|---|
enca 报 language 错误 |
未指定 -L none |
补上 -L none |
uchardet 误判 |
文件太短 | 换 file 或 hexdump |
file 返回 binary |
文件含非文本字节 | 用 hexdump 人工判断 |
vim 返回 utf-8 但实际是 GBK |
Vim 检测策略不同 | 以 file 为准 |
局限性
enca需要语言参数才能稳定工作,不适合全自动脚本。uchardet对短文本误判率高,建议与file交叉验证。- 以上方法均在 WSL2 Ubuntu 24.04 实测;容器里通常只有
file和hexdump,enca/uchardet需要额外安装。 - UTF-8 与 UTF-8 with BOM 通常无法通过这些工具区分。
实测记录
- 环境:WSL2 Ubuntu 24.04,内核 5.15。
file 5.41-3ubuntu0.5:--mime-encoding识别 ASCII/UTF-8/Binary 正常。enca 1.19-1.1build1:需-L none,中文 UTF-8 识别为Universal transformation format 8 bits; UTF-8。uchardet 0.0.8-1build1:中文 UTF-8 识别为UTF-8。vim 2:9.0.1378-2ubuntu3.2:set fileencoding?返回utf-8。hexdump默认安装,中文 UTF-8 字节e5 9f ba e7 a1 80可人工识别。
参考资料
- [1] file(1) – Linux manual page (man7.org)(file(1))
- [2] enca(1) – Debian bookworm — Debian Manpages(enca(1))
- [3] uchardet(1) – Debian bookworm — Debian Manpages(uchardet(1))
- [4] vim(1) – Debian bookworm — Debian Manpages(vim(1))
- [5] hexdump(1) – Linux manual page (man7.org)(hexdump(1))
文中主要命令已在 WSL Ubuntu(24.04)实测并核对其在 Debian 系与通用发行版的文档口径。