Linux环境下shell和vim中乱码原因及消除办法

1. Linux软件运行时的语言环境locale 可以通过命令: locale -a 来显示当前Linux系统支持的所有的语言环境。关于locale,强烈推荐看看 Locale 详解然后 搞明白以下三个环境变量的优先级:LC_ALL>LC_*>LANGlocale相关的各个环境变量 的作用参见这里
2 . 文本文件自身的编码

每个文本文件都有自身的编码方式,如UTF8,ASCII等。

有了以上的知识储备,就可以解决以下问题了:

登录终端中显示的乱码问题

ssh客户端putty/securecrt 登录远程Linux服务器举例子:

要显示中文,首先确保bash中设置的语系是支持中文的,例如采用zh_CN.UTF8编码。可以简单的使用命令:export LANG=zh_CN.UTF8 来设置。如果此时putty中中文仍然是乱码,说明putty自身设置的编码跟刚才设置LANG的编码方式不一样,把putty中的编码方式改成UTF8。之后就可以显示并输入中文了。 如果你用的是bash,可以在~/.bashrc 配置文件中加入上述的命令。这样就不用每次登录后手动设置系统编码了。

vim中显示的乱码问题

在vim中,有以下几个环境变量要理解[可以在vim中使用 :help 关键词  来查看文档]:

1. termencoding

Encoding used for the terminal. This specifies what character encoding the keyboard produces and the display will understand. For the GUI it only applies to the keyboard. 终端使用的编码方式,指定了键盘输出的编码格式和屏幕能够正常显示的编码方式

2. encoding

Sets the character encoding used inside Vim. It applies to text in the buffers, registers, Strings in expressions, text stored in the vim info file, etc. Changing this option will not change the encoding of the existing text in vim. The character encoding of files can be different from 'encoding'. This is specified with 'file encoding'. The conversion is done with icon() or as specified with ‘charconvert'
设置了vim内部缓冲区、寄存器、表达式等中存储的文本的编码方式。它与文件的编码 [ fileencoding ] 可以是不一样的。如果不一样,中间会经过iconv 转换

如果工作用的编码中含有无法转换为内部编码的字符,在这些字符就会丢失。因此,在选择  Vim  的内部编码的时候,一定要使用一种表现能力足够强的编码,例如UTF8,以免影响正常工作。

3. fileencoding

Sets the character encoding for the file of this buffer. When 'file encoding' is different from 'encoding', conversion will be done when reading and writing the file.文件自身的编码方式。如果fileencodingencoding不一致,那么在读取和写入文件时,会对编码方式进行转换。

通过打开文件后设置  fileencoding,我们可以将文件由一种编码转换为另一种编码

4. fileencodings

This is a list of character encodings considered when starting to edit an existing file. When a file is read, Vim tries to use the first mentioned character encoding. If an error is detected, the next one in the list is tried. When an encoding is found that works, 'file encoding' is set to it. If all fail, 'file encoding' is set to an empty string, which means the value of 'encoding' is used.
Note that 'fileencodings' is not used for a new file, the global value of 'file encoding' is used instead.
是一个字符编码的列表。当vim打开一个文件时,会尝试使用列表中的第一个字符编码方式。如果检测到错误,就用列表中的下一个。当找到一个可以正常工作的字符编码方式后,file encoding就被设置成找到的字符编码方式。如果最后都失败了,fileencoding就被设置成空的,这意味者字符的编码方式就跟 encoding变量的值一样了。

这样通过这个列表,Vim可以自动判断文件的编码,自动判断失败时还可手动设定 fileencoding 来指定编码。因此,设置 fileencodings 的时候,一定要把要求严格的、当文件不是这个编码的时候更容易出现解码失败的编码方式放在前面,把宽松的编码方式放在后面。

当vim中遇到乱码时,基本都是由于vim没有能够正确地识别出文件的编码导致的。

首先保证终端里可以正常显示中文,然后使用命令 :set fileencoding=GBK 来设置vim中此文件的正确编码。可以使用命令 :set fileencoding? 查看vim识别出的文件编码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值