linux下編碼轉換

2022-05-08 11:54:12 字數 1902 閱讀 4543

1.什麼是編碼?

還可以參考:

2.linux下經常遇到的編碼問題

如果你需要在linux中操作windows下的檔案,那麼你可能會經常遇到檔案編碼轉換的問題。windows中預設的文

件格式是gbk(gb2312),而linux一般都是utf-8

3.檢視編碼的方法

方法一:file filename

方法二:在vim中可以直接檢視檔案編碼

:set fileencoding

即可顯示檔案編碼格式。

如果你只是想檢視其它編碼格式的檔案或者想解決用vim檢視檔案亂碼的問題,那麼你可以在

~/.vimrc 檔案中新增以下內容:

set encoding=utf-8 fileencodings=ucs-bom,utf-8,cp936

這樣,就可以讓vim自動識別檔案編碼(可以自動識別utf-8或者gbk編碼的檔案),其實就是依照

fileencodings提供的編碼列表嘗試,如果沒有找到合適的編碼,就用latin-1(ascii)編碼開啟。

4.檔案編碼轉換

多平台方法:

iconv        提供標準的程式和api來進行編碼轉換;

convert_encoding.py    基於python的文字檔案轉換工具;

decodeh.py    提供演算法和模組來談測字元的編碼;

linux:

recode    轉換檔案編碼;

utrac    轉換檔案編碼;

cstocs    轉換檔案編碼;

convmv    轉換檔名編碼;

enca    分析給定檔案的編碼;

windows:

cscvt    字符集轉換工具;

linux下檔案編碼轉換:

方法一:

在vim中直接進行轉換檔案編碼,比如將乙個檔案轉換成utf-8格式

:set fileencoding=utf-8

方法二:

iconv 轉換

5.案例:

假如說我們將windows下的乙個utf-8的檔案傳到linux環境下,linux環境下的系統編碼是gb18030,我們cat的時候就會出現亂碼,這個時候就應該想到轉碼了,下面我們來進行試驗:

我是中文編碼utf-8模式~

而linux系統的系統語言設定為:

[root@sor-sys zy]#cat /etc/sysconfig/i18n 

lang=zh_cn.gb18030

sysfont="latarcyrheb-sun16"

這個時候檢視一下檔案的內容及編碼:

[root@sor-sys zy]# file utf-8.sh 

utf-8.sh: utf-8 unicode text, with no line terminators

[root@sor-sys zy]# cat utf-8.sh 

鍩挎垜鏄腑鏂囩紪鐮乁tf-8妯″紡~[root@sor-sys zy]# 

[root@sor-sys zy]# 

這個時候我們就需要轉換編碼了,記得使用iconv

[root@sor-sys zy]# iconv -f utf-8 -t gb18030 utf-8.sh -o gb18030.sh

[root@sor-sys zy]# cat gb18030.sh

??我是中文編碼utf-8模式~[root@sor-sys zy]# 

[root@sor-sys zy]# file gb18030.sh 

gb18030.sh: non-iso extended-ascii text, with no line terminators

[root@sor-sys zy]# 

linux 下的編碼轉換

一 利用iconv函式族進行編碼轉換 在linux上進行編碼轉換時,既可以利用iconv函式族程式設計實現,也可以利用iconv命令來實現,只不過後者是針對檔案的,即將指定檔案從一種編碼轉換為另一種編碼。iconv函式族的標頭檔案是iconv.h,使用前需包含之。include iconv函式族有三...

linux下字元編碼轉換

一 利用iconv函式族進行編碼轉換 iconv函式族的標頭檔案是iconv.h,使用前需包含之。include iconv函式族有三個函式,原型如下 1 iconv t iconv open const char tocode,const char fromcode 此函式說明將要進行哪兩種編碼的...

linux 下命令編碼轉換

用 iconv 沒有就用 piconv,用法 iconv f gbk t utf 8 infile outfile piconv f gbk t utf 8 infile outfile 如果太多檔案,寫個 bash 指令碼,放到要轉換編碼的目錄 裡,指令碼這樣 bin bash iconv ico...