Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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
share|improve this question

2 Answers 2

up vote 5 down vote accepted

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
share|improve this answer
    
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 '13 at 13:01
    
But on second thought is it possible to keep file extension intact? –  Sadi Feb 5 '13 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 '13 at 15:06
1  
@Sadi: you're right, here's how to fix that: unix.stackexchange.com/questions/10241/… –  Flimm Feb 5 '13 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 '13 at 16:03

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, and then replace Turkish characters
#
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
        cat "$filename" | sed -e 's/Ð/Ğ/g' -e 's/ð/ğ/g' -e 's/Þ/Ş/g' -e 's/þ/ş/g' > "$filename.rep" &&
    mv -f "$filename.rep" "$filename"   
done

It also converts certain special characters (which can be modified as needed) after the utf8 conversion.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.