#!/bin/bash
#encode.sh -- encode a file with an indicated encoding
# make sure user give two arguments
[ "$#" != 2 ] && echo "Usage: `basename $0` [to_encoding] [file]" && exit -1
# make sure the second argument is a regular file
[ ! -f $2 ] && echo "the second argument should be a regular file " && exit 1
file=$2
# make sure the first argument is a encoding supported by iconv
iconv -l | grep -q $1
[ $? -ne 0 ] && echo "iconv not support such encoding: $1" && exit -1
to_encoding=$1
# is there a text file?
file_type=`file $file | grep "text"`
[ $? -ne 0 ] && echo "$file is not a text file" && exit -1
# get the old encoding
from_encoding=`echo $file_type | cut -d" " -f 2`
from_encoding=`iconv -l | grep $from_encoding`
[ $? -ne 0 ] && echo "iconv not support the old encoding: $from_encoding"
from_encoding=`echo $from_encoding | cut -d"/" -f 1`
# convert the file from from_encoding to to_encoding
iconv -f $from_encoding -t $to_encoding $file