Linux下 Notepad 类编辑器的编码问题处理
问题成因与总体思路
识别文件编码
file -i my.txt 或 file my.txt(输出如:UTF-8 Unicode text 或 ISO-8859-1 等)。sudo apt-get install enca 或 sudo yum install -y encaenca -L zh_CN my.txt(识别简体中文环境编码,如 GBK/GB2312/UTF-8)。:set fileencoding(显示当前缓冲区的编码)set encoding=utf-8 fileencodings=ucs-bom,utf-8,cp936转换文件编码为 UTF-8
iconv -f GBK -t UTF-8 input.txt -o output.txticonv -f CP1252 -t UTF-8 input.txt -o output.txticonv -f GBK -t UTF-8//IGNORE input.txt -o output.txt:set fileencoding=utf-8 然后 :wq(保存为 UTF-8)。enca -L zh_CN -x UTF-8 *.txt(将当前目录 txt 批量转为 UTF-8)。在 Linux 中正确打开与避免后续乱码
locale -a | grep zh_CN,确保有 zh_CN.UTF-8echo "LANG=zh_CN.UTF-8" | sudo tee /etc/locale.conf,然后 source /etc/locale.conf 或重启会话/系统。常见场景与命令速查
enca -L zh_CN my.txt(多半是 GBK/GB2312)iconv -f GBK -t UTF-8 my.txt -o my_utf8.txtfile -i my_utf8.txt(应见 UTF-8)convmv -f GBK -t UTF-8 --notest *.txt(谨慎操作,先预览)set encoding=utf-8 fileencodings=ucs-bom,utf-8,cp936 并重启 Vim。