Change encoding of all files in folder on Unix, Linux or MacOS

Here is some simple bash script to bulk change encoding of all files in directory. It uses iconv for change of encoding.

#!/bin/bash

if [ $# -ne 3 ]; then
echo “usage: “$0″ dest_directory original_encoding destination_encoding”
exit
fi;

dir=$1
from=$2
to=$3

if [ ! -d $dir ]; then
mkdir $dir
fi

for f in $( ls . ); do
if [ -f $f ]; then
iconv -f $from -t $to $f > $dir$f
fi
done

To run it, create a file recode.sh and paste above code into it. Then in terminal run

chmod +x recode.sh

adn then just

./recode.sh encoded_dir/ ISO-8859-13 UTF-8

Command mentioned above recodes all files in current directory from  ISO-8859-13 encoding to UTF-8 and copies new files to encoded_dir/ directory.

5 Responses to “Change encoding of all files in folder on Unix, Linux or MacOS”

  1. Tdk Says:

    First, thanks for the script.
    Could yo please help me making this script recursive to the current folder?
    Thanks

  2. jarik Says:

    Hi, I wrote something, it seems to work, but pease try it and let me know ;) if everything is ok – I’ll update the post with improved version ;)

    #!/bin/bash

    if [ $# -ne 4 ]; then
    echo “usage: “$0″ source_directory dest_directory original_encoding destination_encoding”
    exit
    fi;

    dir_from=$1
    dir=$2
    from=$3
    to=$4

    if [ ! -d $dir ]; then
    mkdir $dir
    fi

    for f in $( ls $dir_from ); do
    file=$dir_from$f

    if [ -d $file ]; then
    $0 $file”/” $dir$f”/” $from $to
    fi
    if [ -f $file ]; then
    iconv -f $from -t $to $file > $dir$f
    fi

    done

  3. Tdk Says:

    Again, thanks a lot.
    I already re-enconded the whole folder I needed one by one with your first script, I tested this one and it just works for one leve down and make something strange with the names, I’ll work with this as a base and try to make it to get a complete re-encoded copy of a folder with the same structure. (I guess that’s how someone who tries to do what I tried would like).

    Do you have creative-common license or something for your blog? Because I post tech stuff on one section of my blog (tadekchavez.com) (spanish) and would like to “re-post/translate” this helpful post to the community, of course with the respective credit for you.

    Thanks in advance, this was really helpful.

  4. jarik Says:

    To be honest, I don’t like reading all that law stuff (licences), but as long as you leave a link to the source – you can make it available on your page ;) Maybe you could point me to some appropriate licence?

    About the names – maybe you have not used slach “/” at the end of folders (source and dest)?
    by the way, ” should be corrected when you copy-paste the script to the file (I think you managed with this :))

  5. Tdk Says:

    Oh! yes, I forgot to make that correction, I noticed the ” sign wasn’t correct, with that I wouldn’t have this running!
    Cheers!

Leave a Reply