Change encoding of txt file

When I write :

file file1.txt 

I have this output : Little-endian UTF-16 Unicode text, with CR line terminators

Then if I write :

file file2.txt 

I have : ASCII text

file2.txt is created by making :

echo $var > "file2.txt"

I would like file2.txt have the same encoding than file1.txt. How can I do that ?


Solution 1:

You can use iconv to convert the encoding of the file:

iconv -f ascii -t utf16 file2.txt > another.txt

another.txt should then have the desired encoding.

You could also try this:

echo $var | iconv -f ascii -t utf16 > "file2.txt"

Solution 2:

Use iconv:

echo "$var" | iconv --from-code=utf-8 --to-code=utf-16le --output=file2.txt