Linux command for converting encoding


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?



Thank you for using forums.

What about this simple shell script:


file -i $1 | grep -qi ascii

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

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. and make it executable:

$ chmod +x

Once ready execute the following:

$ echo TEST > file.txt
$ file file.txt
file.txt: ASCII text
$ ./ file.txt
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.