Skip to content

Instantly share code, notes, and snippets.

@glejeune
Created October 21, 2011 13:39
Show Gist options
  • Select an option

  • Save glejeune/1303874 to your computer and use it in GitHub Desktop.

Select an option

Save glejeune/1303874 to your computer and use it in GitHub Desktop.
Find and convert file encoding
#!/bin/sh
get_encoding() {
FILE=$1
file --mime-encoding $FILE | awk '{print $2}'
}
get_type() {
FILE=$1
file $FILE | awk '{print $2}'
}
# -- main --
FROM_ENC=-
TO_ENC=-
KEEP_OLD=yes
ICONV_OK=$(perl -e "print \"$(iconv --version 2> /dev/null | head -1)\" =~ /iconv/")
if [ "X$ICONV_OK" != "X1" ] ; then
echo "iconv is not installed!"
exit 1
fi
args=`getopt f:t:S $*`
if [ $? != 0 ] ; then
echo 'Usage: ...'
exit 2
fi
set -- $args
for i do
case "$i"
in
-f)
FROM_ENC=$2 ; shift ;
shift;;
-t)
TO_ENC=$2 ; shift ;
shift;;
-S)
KEEP_OLD=no ;
shift;;
--)
shift ; break;;
esac
done
for i do
FILE=$i
for f in $(find $FILE) ; do
if [ "$(get_type $f)" != "directory" ] ; then
ENC=$(get_encoding $f)
CHANGE=no
if [ "$ENC" == "$FROM_ENC" ] ; then
CHANGE=yes
else
if [ "$FROM_ENC" == "-" ] ; then
CHANGE=yes
fi
fi
if [ "$TO_ENC" == "-" ] ; then
CHANGE=no
fi
if [ "$CHANGE" == "yes" ] ; then
echo $f from $ENC to $TO_ENC
iconv -f $ENC -t $TO_ENC $f > $f.$TO_ENC
mv $f $f.$ENC
mv $f.$TO_ENC $f
if [ "$KEEP_OLD" == "no" ] ; then
rm -f $f.$ENC
fi
else
echo $f : $ENC
fi
fi
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment