photo credit: LCD RED TEXT via photopin (license)

Convert a file encoding to UTF-8 from a shell script

Tags: ,

Today I had the situation where I had to convert a bunch of files to the UTF-8 encoding. All source files where in different encoding but they had to be saved in UTF-8 in order for the application to work properly. To do this I created a simple shell script.
This is the function that does all the magic:

What it does, is it checks the encoding of the current file, by using the file -command. Then, if the file isn’t already UTF-8 encoded, it uses chardet  to detect the encoding of the file. And last but not least, it uses iconv  to change the encoding from one to another.
You can use it in your shell script like this:

Simple as that!

Visitors give this article an average rating of 4.5 out of 5.

How would you rate this article?

One thought on “Convert a file encoding to UTF-8 from a shell script”

  1. PixinParis says:

    Thanks a lot for this script, I was trying to do exactly the same thing! Saved me the trouble!

Leave a Reply