Linux下文件編碼格式轉換

        最近把項目放到github上,但是發現代碼中註釋的中文部分有些是亂碼,檢查後發現是因爲我的Centos裝在虛擬機上,而我是在Windows環境下通過UE來寫代碼的,而UE默認是使用ASCII編碼。

        所以希望在Linux上使用命令來批量轉換編碼格式。

 

        查了資料後發現可以使用iconv命令。

 

        首先使用 file 命令來檢測文件的類型

        例如:filetest.cpp

        輸出:ISO-8859 Cprogram text

 

        iconv命令的參數說明:

 

        -l    列出所有已知的字符集

        -f    原始文本編碼

        -t    輸出文本編碼

        -o    輸出文件名

        -s    關閉警告

 

例子:

        iconv-f GB2312 -t UTF-8 test.cpp > test_utf.cpp

        因爲iconv默認輸出到標準輸出,所以我們需要重定向到一個其他文件。(這裏不能重定向到自身,否則會清空文件內容)

 

        如果想要把輸出內容直接輸出到當前文件,可以這樣用:

        iconv-f GB2312 -t UTF-8 -o test.cpp test.cpp


    附上我自己用的編碼轉換腳本 iconvfa.sh :

    可以轉換單個文件: ./iconvfa.sh [file_name]

    以遞歸方式地方式轉換文件夾下所有文件: ./iconvfa.sh -R [dir_name]


#!/bin/env bash

function show_help
{
    echo "Usage:"
    echo "  iconvfa.sh [option] [file|dir]"
    echo -e "  from GB2312 to UTF-8, the old file will be replaced by the new converted file\n"
    echo "Options:"
    echo "  -R: convert files recursively, the following parameter should be the directory name"
}

# param 1: directory name
function convert_rescursive()
{
   local dir_path=`echo $1 | sed 's/\(.*\)\/$/\1/g'`
   local dir_names=`ls ${dir_path} -l | awk '/^d/{print $NF}'`
   
   # convert files in this directory
   local file_names=`ls ${dir_path} -l | awk '/^-/{print $NF}'`
   for file in ${file_names}
   do
       iconv -f ${from_code} -t ${to_code} ${dir_path}/${file} &> /dev/null
       if [ $? == 0 ]; then
           iconv -f ${from_code} -t ${to_code} < ${dir_path}/${file} > $@.$$$$
           cp $@.$$$$ ${dir_path}/${file}
           rm -f $@.$$$$
           echo "File ${dir_path}/${file} is formatted."
       fi
   done

   # if the directory has no other directory, return 0
   if [ "${dir_names}X" == "X" ]; then
       return 0
   fi

   # continue convert files in directories recursively
   for dir in ${dir_names}
   do
       convert_rescursive "${dir_path}/${dir}"
   done 
}

# defines
from_code="GB2312"
to_code="UTF-8"

case "$1" in
"-R")
    ls $2 &> /dev/null
    if [ $? != 0 -o "$2X" == "X" ]; then
        echo "#### error: please check the directory name follow the '-R' option!"
        exit 1
    fi
    convert_rescursive $2
    ;;
"")
    show_help
    ;;
*)
    iconv -f ${from_code} -t ${to_code} $1 &> /dev/null
    if [ $? == 0 ]; then
        iconv -f ${from_code} -t ${to_code} < $1 > $@.$$$$
        cp $@.$$$$ $1
        rm -f $@.$$$$
        echo "File $1 is formatted."
    else
        echo "Convert wrong!"
    fi
    ;;
esac

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章