3

I think the ideal solution for me is a Nautilus Script that performs encoding conversion on selected files.

The following script reads the encoding of a selected file and performs utf8 conversion if it's not utf8, but I couldn't figure out how to make it work on multiple files:

CHARSET="$(file -bi "$1"|awk -F "=" '{print $2}')"
if [ "$CHARSET" != utf-8 ]; then
iconv -f "$CHARSET" -t utf8 "$1" -c -o "$1.utf8"
fi

2 Answers 2

5

Let's say your script is named convert-to-utf-8.sh. Here's how you would make it work across multiple files:

for filename in file1 file2 file3 ; do ./convert-to-utf-8.sh "$filename" ; done

You could incorporate that for-loop in the script itself, like this:

for filename in "$@"; do
    CHARSET="$(file -bi "$filename"|awk -F "=" '{print $2}')"
    if [ "$CHARSET" != utf-8 ]; then
        iconv -f "$CHARSET" -t utf8 "$filename" -c -o "$filename.utf8"
    fi
done

You could then run the script with multiple filenames like this:

./convert-to-utf-8.sh file1 file2 file3
5
  • Thank you very much for teaching me this for-loop thing, it's magic! The revised code in the middle does exactly what I want!
    – Sadi
    Feb 5, 2013 at 13:01
  • But on second thought is it possible to keep file extension intact?
    – Sadi
    Feb 5, 2013 at 13:40
  • Thanks, but I tried it already and it seems inconv loses the input file (replaced by output file) before the operation is completed on longish files; and I get only half the file in the end.
    – Sadi
    Feb 5, 2013 at 15:06
  • 1
    @Sadi: you're right, here's how to fix that: unix.stackexchange.com/questions/10241/…
    – Flimm
    Feb 5, 2013 at 15:36
  • Thank you so much! I've decided to show the result as a separate answer so that it might be useful to others as well.
    – Sadi
    Feb 5, 2013 at 16:03
2

Here's a nice and simple Nautilus Script that I've managed to write thanks to Flimm as seen in the answer above:

#!/bin/sh
#Nautilus Script to determine encoding of selected file(s) and convert to utf8 if necessary
#
for filename in $@; do
    CHARSET="$(file -bi "$filename"|awk -F "=" '{print $2}')"
    if [ "$CHARSET" != utf-8 ]; then
        iconv -f "$CHARSET" -t utf8 "$filename" -c -o "$filename.utf8" &&
        mv -f "$filename.utf8" "$filename"
    fi
done

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .