shell脚本使用iconv 批量改变文件编码

第一个版本:

用法示例:

cd ~/workspace/XXXProject
~/iconv_shell.sh ./ *java
#!/bin/bash 
if [ "$#" != "2" ]; then 
    echo "Usage: `basename $0` dir filter" 
    exit 
fi
 
dir=$1 
filter=$2 
echo $1
 
for file in `find $dir -name "$2"`; do 
    echo "$file" 
    iconv -f gbk -t utf8 -o $file $file 
done

另一个版本:

用法和功能:
1.有两个参数,即需要转换的文件和希望转换的编码。
2.使用 iconv 工具转换,并将目标编码名称加入到文件名中以示区别。

#!/bin/bash
#Author:digglife
#Description:Convert the charset of text file.
#version:0.2
#Date:2011/05/12
#To Be Resovled:
#  1.get filename without using $fileExtension varable.

#Get the parameters
file=$1
to_charset=$2

#Get the first character of the $file
first_char=${file:0:1}

#Test if the file exists,break if it doesn't
if [ ! -f "$file" ];then
    echo "$file,No such file or directory"
    exit 1
#If the given $file contains the directory,get the basename of it,and change dir to its directory.
elif [ first_char="/" ];then
    full_filename=$(basename $file)
    cd $(dirname $file)
else
    full_filename=$file
fi

#Split the file extention and filename
file_extension=$(echo $full_filename | sed 's/^.*.//g')
filename=${full_filename%.$file_extension}

#Get the original charset
charset_org=$(file -I $full_filename | sed 's/^.*charset=//g')

#Convert the charset,and change the full filename
iconv -c -f $charset_org -t $to_charset $full_filename > $filename.$to_charset.$file_extension

Shell编码知识总结:

  1. 通过${variable:index:index}的方式可以取得String的部分字符,非常方便。上述脚本就用到了这个命令来取得文件名的头文字,以判断是否带有路径。
  2. 文件判断语句中,if [ ! -f $file ]中[的后面和]的前面是有空格的,如果没有则提示错误。这一次也好好地熟悉了一下条件判断语句的写法。以前还以为是else if的,原来可以用elif。
  3. sed用法。主要是sed替代命令的用法,s/re/re/g这种命令结合正则表达式的的确确非常好用。
  4. ##和%%用于文本操作时的用法。要点有二,#从前面删起、%从后面删起;重复利用时删除更长的那个(这个只有举例说明,文字词不达意)
  5. file -I可以用于判断文本编码。
  6. iconv不能生成文件,仅用于标准输出,如果要生成文件,需要利用>输出。
  7. 如果文件路径中含有~(home目录)时,shell会自动将其转换为标准的绝对路径,所以在判断参数1是否带有文件路径时,只需判断第一个字符是否为/,而不用管~。

猜你喜欢

转载自wuhuizhong.iteye.com/blog/1424132
今日推荐