Changing character sets for ALL files in a directory to UTF-8

Hello,

I have over 300 script files in a directory that were created using a mixture of the following character sets:

Windows-1251
Windows-1252
ISO 8859-1

This causes a number of problems.

For example, when displayed as a webpage, the header could be created with one charset, the body with another and the footer with another.

So I need to convert the contents of ALL files with the extension .pl or .cgi or .php or .txt or .tpl to UTF-8.

How can this be done with PERL?

Thanks!
LVL 16
hankknightAsked:
Who is Participating?
 
mjcoyneCommented:
Are these CGI files?  Do you mean to say that the Perl scripts create web pages that use XML document type declarations (DTD) and that these declarations specify different character types?

So, some web pages created by these scripts have something like:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

while others might have:

<?xml version="1.0" encoding="ISO 8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

and you need them all to be consistant?

I guess I might be confused about what you mean by the "script files...were created using a mixture of...character sets".  Do you mean the files *themselves* were created (written) with mixed character sets, or the files that the scripts create as *output* contain mixed character sets?
0
 
mjcoyneCommented:
If it's what I think, it'd be a simple regular expression problem.  For example:

#!/usr/bin/perl -w
use strict;

while (<DATA>) {
    s/encoding=".+?"/encoding="UTF-8"/;
    print;
}

__DATA__
<?xml version="1.0" encoding="Windows-1251"?>
<?xml version="1.0" encoding="Windows-1252"?>
<?xml version="1.0" encoding="ISO 8859-1"?>

Couple this with File::Find to find all your .pl , .cgi, .php, .txt or .tpl files, open each matching file, replace the encoding line with the one you want, and print the file to a new file.
0
 
ahoffmannCommented:
# I guess you need something like following code snippet:

use Encode;
# ... some code to read the file content here
from_to($content, "cp1250", "utf8");
# .. some other file
from_to($content, "iso-8859-1", "utf8");

# please read  man Encode carefully first
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.