Convert to unicode linux

How to convert \uXXXX unicode to UTF-8 using console tools in *nix

I use curl to get some URL response, it’s JSON response and it contains unicode-escaped national characters like \u0144 (ń) and \u00f3 (ó) . How can I convert them to UTF-8 or any other encoding to save into file?

11 Answers 11

Might be a bit ugly, but echo -e should do it:

-e interprets escapes, -n suppresses the newline echo would normally add.

Note: The \u escape works in the bash builtin echo , but not /usr/bin/echo .

As pointed out in the comments, this is bash 4.2+, and 4.2.x have a bug handling 0x00ff/17 values (0x80-0xff).

@cbuckley it was bash (as I added to the post, I figured out it was the bash builtin), but zsh’s echo works with \u too. csh ‘s does not, however.

@KrzysztofWolny The example is already in my post, either store the URL you’re trying to get into the URL variable, or just replace it manually. $(command) executes command , so $(curl $URL) fetches the page at $URL .

I don’t know which distribution you are using, but uni2ascii should be included.

$ sudo apt-get install uni2ascii 

It only depend on libc6, so it’s a lightweight solution (uni2ascii i386 4.18-2 is 55,0 kB on Ubuntu)!

$ echo 'Character 1: \u0144, Character 2: \u00f3' | ascii2uni -a U -q Character 1: ń, Character 2: ó 

That allow to display it, but not to save/convert it. even with uni2ascii unicode.txt > newfile.txt . iconv do it well

echo ‘Character 1: \u0144, Character 2: \u00f3’ | ascii2uni -a U -q > newfile.txt clearly works and saves the output into newfile.txt .

I found native2ascii from JDK as the best way to do it:

native2ascii -encoding UTF-8 -reverse src.txt dest.txt 

Assuming the \u is always followed by exactly 4 hex digits:

#!/usr/bin/perl use strict; use warnings; binmode(STDOUT, ':utf8'); while (<>) < s/\\u([0-9a-fA-F])/chr(hex($1))/eg; print; > 

The binmode puts standard output into UTF-8 mode. The s. command replaces each occurrence of \u followed by 4 hex digits with the corresponding character. The e suffix causes the replacement to be evaluated as an expression rather than treated as a string; the g says to replace all occurrences rather than just the first.

You can save the above to a file somewhere in your $PATH (don’t forget the chmod +x ). It filters standard input (or one or more files named on the command line) to standard output.

Again, this assumes that the representation is always \u followed by exactly 4 hex digits. There are more Unicode characters than can be represented that way, but I’m assuming that \u12345 would denote the Unicode character 0x1234 (ETHIOPIC SYLLABLE SEE) followed by the digit 5 .

Читайте также:  Как восстановить рут пароль линукс

In C syntax, a universal-character-name is either \u followed by exactly 4 hex digits, or \U followed by exactly 8 hexadecimal digits. I don’t know whether your JSON responses use the same scheme. You should probably find out how (or whether) it encodes Unicode characters outside the Basic Multilingual Plane (the first 2 16 characters).

Источник

How to Convert Files to UTF-8 Encoding in Linux

In this guide, we will describe what character encoding and cover a few examples of converting files from one character encoding to another using a command line tool. Then finally, we will look at how to convert several files from any character set (charset) to UTF-8 encoding in Linux.

As you may probably have in mind already, a computer does not understand or store letters, numbers or anything else that we as humans can perceive except bits. A bit has only two possible values, that is either a 0 or 1 , true or false , yes or no . Every other thing such as letters, numbers, images must be represented in bits for a computer to process.

In simple terms, character encoding is a way of informing a computer how to interpret raw zeroes and ones into actual characters, where a character is represented by set of numbers. When we type text in a file, the words and sentences we form are cooked-up from different characters, and characters are organized into a charset.

There are various encoding schemes out there such as ASCII, ANSI, Unicode among others. Below is an example of ASCII encoding.

Character bits A 01000001 B 01000010

In Linux, the iconv command line tool is used to convert text from one form of encoding to another.

You can check the encoding of a file using the file command, by using the -i or —mime flag which enables printing of mime type string as in the examples below:

$ file -i Car.java $ file -i CarDriver.java

Check File Encoding in Linux

The syntax for using iconv is as follows:

$ iconv option $ iconv options -f from-encoding -t to-encoding inputfile(s) -o outputfile

Where -f or —from-code means input encoding and -t or —to-encoding specifies output encoding.

To list all known coded character sets, run the command below:

List Coded Charsets in Linux

Convert Files from UTF-8 to ASCII Encoding

Next, we will learn how to convert from one encoding scheme to another. The command below converts from ISO-8859-1 to UTF-8 encoding.

Consider a file named input.file which contains the characters:

Let us start by checking the encoding of the characters in the file and then view the file contents. Closely, we can convert all the characters to ASCII encoding.

After running the iconv command, we then check the contents of the output file and the new encoding of the characters as below.

$ file -i input.file $ cat input.file $ iconv -f ISO-8859-1 -t UTF-8//TRANSLIT input.file -o out.file $ cat out.file $ file -i out.file

Convert UTF-8 to ASCII in Linux

Note: In case the string //IGNORE is added to to-encoding, characters that can’t be converted and an error is displayed after conversion.

Читайте также:  Can read superblock linux

Again, supposing the string //TRANSLIT is added to to-encoding as in the example above (ASCII//TRANSLIT), characters being converted are transliterated as needed and if possible. Which implies in the event that a character can’t be represented in the target character set, it can be approximated through one or more similar looking characters.

Consequently, any character that can’t be transliterated and is not in target character set is replaced with a question mark (?) in the output.

Convert Multiple Files to UTF-8 Encoding

Coming back to our main topic, to convert multiple or all files in a directory to UTF-8 encoding, you can write a small shell script called encoding.sh as follows:

#!/bin/bash #enter input encoding here FROM_ENCODING="value_here" #output encoding(UTF-8) TO_ENCODING="UTF-8" #convert CONVERT=" iconv -f $FROM_ENCODING -t $TO_ENCODING" #loop to convert multiple files for file in *.txt; do $CONVERT "$file" -o "$.utf8.converted" done exit 0

Save the file, then make the script executable. Run it from the directory where your files ( *.txt ) are located.

$ chmod +x encoding.sh $ ./encoding.sh

Important: You can as well use this script for general conversion of multiple files from one given encoding to another, simply play around with the values of the FROM_ENCODING and TO_ENCODING variable, not forgetting the output file name «$.utf8.converted» .

For more information, look through the iconv man page.

To sum up this guide, understanding encoding and how to convert from one character encoding scheme to another is necessary knowledge for every computer user more so for programmers when it comes to dealing with text.

Lastly, you can get in touch with us by using the comment section below for any questions or feedback.

Источник

Как преобразовать файлы в кодировку UTF-8 в Linux

В этом руководстве мы опишем, что такое кодировка символов, и рассмотрим несколько примеров преобразования файлов из одной кодировки символов в другую с помощью инструмента командной строки. Затем, наконец, мы рассмотрим, как преобразовать несколько файлов из любого набора символов (charset) в кодировку UTF-8 в Linux.

Как вы, возможно, уже имеете в виду, компьютер не понимает и не хранит буквы, цифры или что-либо еще, что мы, люди, можем воспринимать, кроме битов. Бит имеет только два возможных значения: 0 или 1 , true или false , да или нет . Любая другая вещь, такая как буквы, цифры, изображения, должна быть представлена в битах для обработки компьютером.

Проще говоря, кодировка символов — это способ сообщить компьютеру, как интерпретировать необработанные нули и единицы в фактические символы, где символ представлен набором чисел. Когда мы набираем текст в файле, слова и предложения, которые мы формируем, состоят из разных символов, а символы организованы в кодировку.

Существуют различные схемы кодирования, такие как ASCII, ANSI, Unicode и другие. Ниже приведен пример кодировки ASCII.

Character bits A 01000001 B 01000010

В Linux инструмент командной строки icon используется для преобразования текста из одной формы кодировки в другую.

Читайте также:  Ftp команды в линуксе

Вы можете проверить кодировку файла с помощью команды file, используя флаг -i или —mime , который разрешает печать типа mime. строка, как в примерах ниже:

$ file -i Car.java $ file -i CarDriver.java

Синтаксис использования icon следующий:

$ iconv option $ iconv options -f from-encoding -t to-encoding inputfile(s) -o outputfile

Где -f или —from-code означает входную кодировку, а -t или —to-encoding указывает выходное кодирование.

Чтобы получить список всех известных кодированных наборов символов, выполните следующую команду:

Преобразование файлов из кодировки UTF-8 в кодировку ASCII

Далее мы узнаем, как преобразовать одну схему кодирования в другую. Приведенная ниже команда преобразует кодировку ISO-8859-1 в UTF-8.

Рассмотрим файл с именем input.file , который содержит символы:

Начнем с проверки кодировки символов в файле, а затем просмотрим содержимое файла. Мы можем преобразовать все символы в кодировку ASCII.

После выполнения команды icon мы проверяем содержимое выходного файла и новую кодировку символов, как показано ниже.

$ file -i input.file $ cat input.file $ iconv -f ISO-8859-1 -t UTF-8//TRANSLIT input.file -o out.file $ cat out.file $ file -i out.file

Примечание. В случае добавления строки //IGNORE в to-encoding символы, которые не могут быть преобразованы, и ошибка отображается после преобразования.

Опять же, предположим, что строка //TRANSLIT добавлена в to-encoding, как в приведенном выше примере (ASCII//TRANSLIT), преобразуемые символы транслитерируются по мере необходимости и, если возможно, . Это означает, что в случае, если символ не может быть представлен в целевом наборе символов, он может быть аппроксимирован одним или несколькими похожими символами.

Следовательно, любой символ, который не может быть транслитерирован и не входит в целевой набор символов, в выводе заменяется знаком вопроса (?) .

Преобразование нескольких файлов в кодировку UTF-8

Возвращаясь к нашей основной теме, чтобы преобразовать несколько или все файлы в каталоге в кодировку UTF-8, вы можете написать небольшой сценарий оболочки с именем encoding.sh следующим образом:

#!/bin/bash #enter input encoding here FROM_ENCODING="value_here" #output encoding(UTF-8) TO_ENCODING="UTF-8" #convert CONVERT=" iconv -f $FROM_ENCODING -t $TO_ENCODING" #loop to convert multiple files for file in *.txt; do $CONVERT "$file" -o "$.utf8.converted" done exit 0

Сохраните файл, затем сделайте скрипт исполняемым. Запустите его из каталога, где находятся ваши файлы ( *.txt ).

$ chmod +x encoding.sh $ ./encoding.sh

Важно: вы также можете использовать этот скрипт для общего преобразования нескольких файлов из одной заданной кодировки в другую, просто поэкспериментируйте со значениями FROM_ENCODING и переменную TO_ENCODING , не забывая имя выходного файла \&#36 .utf8.converted\ .

Для получения дополнительной информации просмотрите справочную страницу icon.

Подводя итог этому руководству, понимание кодировки и того, как преобразовать одну схему кодировки символов в другую, является необходимым знанием для каждого пользователя компьютера, особенно для программистов, когда дело доходит до работы с текстом.

Наконец, вы можете связаться с нами, используя раздел комментариев ниже для любых вопросов или отзывов.

Источник

Оцените статью
Adblock
detector