AppleScript for converting text to UTF 8

First time posting, please be gentle:)

I don’t know if you have ever encountered the following problem “ it happens to me quite often. When I download a (Hungarian) subtitle for a movie, it is often made on a Windows system, so the special characters are messed up when I try to attach it to a movie.

I found out, that this happens because of the encoding of the text. I have to convert it to UTF 8.
I can do it manually, but it is a tiresome thing to repeat all the time: I need to automate it somehow.

I found out, that this could be done AppleScript.

I want to create a Folder Action, so the AppleScript would be triggered by dropping any files into this folder (I would call it “subs”).
The scripts would scan the folder for text files, and convert all the files to UTF 8.
Can it be done?

Would you be so kind to help me?
I have never written an AppleScript before, so I’m totally noob, but I did some research, and I’m starting to understand the basics, but I still have no idea how to do this.

Thanks for reading this!

Regards,
Domonkos

Hi,

this depends on the input text encoding.
With the shell command iconv you can convert text to different character sets

This assumes the western latin encoding, you can change the encoding in the property line according to the encodings described in iconv_open (3)

Save the script as application and drop files onto it.
Be aware that the original files are overwritten


property inputEncoding : "ISO-8859-1"

on open theseFiles
	repeat with aFile in theseFiles
		set utf8Text to (do shell script "cat " & quoted form of POSIX path of aFile & " | iconv -f " & inputEncoding & " -t UTF-8")
		writeToDisk from utf8Text into (aFile as text)
	end repeat
end open

on writeToDisk from |data| into target
	try
		set fileDescriptor to open for access file target with write permission
		write |data| to fileDescriptor as «class utf8»
		close access fileDescriptor
	on error
		try
			close access file target
		end try
	end try
end writeToDisk