Linux下文件编码格式转换
来源:互联网 发布:js 指定时间戳 编辑:程序博客网 时间:2024/06/02 08:51
最近把项目放到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 bashfunction 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 namefunction 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 }# definesfrom_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
- linux下文件转换编码格式
- Linux下文件编码格式转换
- linux下文件编码格式转换方法
- linux系统下文件编码格式的转换
- Linux下文件编码转换
- LINUX下文件字符集编码转换
- Linux下文件字符集编码转换
- LINUX下文件字符集编码转换
- linux下文件编码批量转换
- Linux下文件字符集编码转换
- Linux下文件字符集编码转换
- 使用 Java 对 Linux 下文件编码格式进行批量转换
- 使用 Java 对 Linux 下文件编码格式进行批量转换
- 使用 Java 对 Linux 下文件编码格式进行批量转换
- linux下文件编码格式转换方法(gb18030/utf-8)
- [转]linux下文件编码格式转换方法(gb18030/utf-8)
- LINUX下文件字符集编码查看与编码转换
- Ubuntu Linux系统下文件编码转换的技巧
- 被遗忘的PHP5.3新特性——Phar
- Linux RHCE 认证复习题100道
- 李慶涵 晩沙 人之酒量
- 腾讯下一个重点:硬件;硬件自身的未来也正进入多元化发展
- Handle UTF8 file with BOM
- Linux下文件编码格式转换
- java----网络编程(一)TCP
- 高强
- 读者与写者问题
- frame.pack()
- 详解SESSION与COOKIE的区别
- Workspace in use or cannot be created, choose a different one.--错误解决办法
- Python方法定义,以及有参
- unity 3d中使用BMFont制作清晰字体