1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| #! /bin/bash
//bin/bash -c "exec java bsh.Interpreter $0 $1 $2";exit
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.regex.*;
String nomDuCodage(String demande)
{
but = demande;
switch (demande)
{
case "ISO-8859":
but = "ISO-8859-1";
break;
case "Perl5":
but = "UTF-8"; // je suppose
break;
case "empty":
but = null;
break;
}
return but;
}
nompourencodageentree = null;
nompourencodagesortie = null;
if (bsh.args.length == 0)
{
print("codeconv.bsh encodageEntree encodageSortie");
print("-> lecture du nom du fichier sur l'entree standard \n (s'adpate au resultat de la commande file)");
print("*");
print("utitilisation avec 'file', pour designer automatiquement l'encodage d'entree : ");
print("file `find ...options...` | codeconv.bsh UTF-8\n");
System.exit(0);
}
if (bsh.args.length > 1)
{
nompourencodageentree = bsh.args[0];
nompourencodagesortie = bsh.args[1];
print("encodage d'entree (ou par defaut) : "+nompourencodageentree);
print("encodage de sortie : "+nompourencodagesortie);
}
else
{
nompourencodagesortie = bsh.args[0];
print("encodage d'entree donne par la sortie de la commande 'file'");
print("encodage de sortie : "+nompourencodagesortie);
}
pattfile = Pattern.compile("(.*?):\\s+(\\S*) ?.*");
scan = new Scanner(System.in);
tmp = File.createTempFile("codeconv", "tmp");
tmp.deleteOnExit();
while (scan.hasNextLine())
{
// lecture et transformation du fichier vers un temporaire
ligne = scan.nextLine();
match = pattfile.matcher(ligne);
nomfichier = ligne;
if (match.matches())
{
nomfichier = match.group(1);
nompourencodageentree = nomDuCodage(match.group(2));
}
if (nompourencodageentree != null)
{
if (!nompourencodageentree.equals(nompourencodagesortie))
{
in = new File(nomfichier);
inlength = in.length();
inf = new FileInputStream(in);
ouf = new FileOutputStream(tmp);
inc = inf.getChannel();
ouc = ouf.getChannel();
inmap = inc.map(FileChannel.MapMode.READ_ONLY, 0, inlength);
codein = Charset.forName(nompourencodageentree).newDecoder();
cbin = codein.decode(inmap);
codeout = Charset.forName(nompourencodagesortie).newEncoder();
cout = codeout.encode(cbin);
ouc.write(cout);
inc.close();
ouc.close();
// remplacement de l'original par le nouveau
tmp = new File(tmp.getCanonicalPath());
oufori = new FileOutputStream(in);
inftmp = new FileInputStream(tmp);
oucori = oufori.getChannel();
inctmp = inftmp.getChannel();
oucori.transferFrom(inctmp, 0, tmp.length());
oucori.close();
inctmp.close();
print("+ "+nomfichier+" ("+nompourencodageentree+" -> "+nompourencodagesortie+") FAIT.");
}
else
print("+ "+nomfichier+" ("+nompourencodageentree+") PASSE.");
}
else
print("+ "+nomfichier+" VIDE.");
} |