Linux command for converting encoding


#1

I need to use the command “file -i” to identify the file encoding and then convert to another encoding, such as ascii to utf-8.

My plan is to file -i >> logfile
Next is to check logfile for the encoding type and if ascii, convert to utf-8

there should only be the single line from the file -i

So depending on the encoding type, execute the iconv to convert from one to the other encoding. can this be done using scripting?


#2

Hi,

Thank you for using linuxconfig.org forums.

What about this simple shell script:

#/bin/bash

file -i $1 | grep -qi ascii

if [ $? -eq 0 ]; then
    echo "ASCII FILE"
    echo "Executing some command"
else
    echo "NO ASCII FILE"
    echo "Converting to UTF-8 command"
fi

We first check whether the file is ASCII. Then based on the result in $? we use bash conditionals and act accordingly.

Copy the above code into file called eg. convert.sh and make it executable:

$ chmod +x convert.sh

Once ready execute the following:

$ echo TEST > file.txt
$ file file.txt
file.txt: ASCII text
$ ./convert.sh file.txt
ASCII FILE
Executing some command

Visit the following page for more information on how to create and execute bash scripts.

Note sure if this is exactly what you need but it should give you a good start.

Hope this helps.

Lubos