Проверка исходного файла ASCII
Для официальной документации по Ubuntu, где исходные английские файлы находятся в docbook xml, требуется только символы ASCII. Мы используем командную строку "checker" (см. Здесь).
grep --color='auto' -P -n "[\x80-\xFF]" *.xml
Однако эта команда имеет недостаток, очевидно, не на всех компьютерах, она пропускает некоторые строки с символами, отличными от ASCII, что может привести к ложному результату OK.
У кого-нибудь есть лучшее предложение для командной строки ASCII Checker?
Заинтересованные лица могут использовать этот файл (текстовый файл, а не файл docbook xml) в качестве контрольного примера. Первые три строки с не ASCII-символами - это строки 9, 14 и 18. Строки 14 и 18 были пропущены при проверке:
$ grep --color='auto' -P -n "[\x80-\xFF]" install.en.txt | head -13
9:Appendix F, GNU General Public License.
330:when things go wrong. The Installation Howto can be found in Appendix A,
337:Chapter 1. Welcome to Ubuntu
359:1.1. What is Ubuntu?
394:1.1.1. Sponsorship by Canonical
402:1.2. What is Debian?
456:1.2.1. Ubuntu and Debian
461:1.2.1.1. Package selection
475:1.2.1.2. Releases
501:1.2.1.3. Development community
520:1.2.1.4. Freedom and Philosophy
534:1.2.1.5. Ubuntu and other Debian derivatives
555:1.3. What is GNU/Linux?
3 ответа
Если вы хотите искать не-ASCII-символы, возможно, вам следует инвертировать поиск, чтобы исключить ASCII-символы:
grep -Pn '[^\x00-\x7F]'
Например:
$ curl https://help.ubuntu.com/16.04/installation-guide/amd64/install.en.txt -s | grep -nP '[^\x00-\x7F]' | head
9:Appendix F, GNU General Public License.
14:(codename "‘Xenial Xerus’"), for the 64-bit PC ("amd64") architecture. It also
18:━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
330:when things go wrong. The Installation Howto can be found in Appendix A,
337:Chapter 1. Welcome to Ubuntu
359:1.1. What is Ubuntu?
368: • Ubuntu will always be free of charge, and there is no extra fee for the "
372: • Ubuntu includes the very best in translations and accessibility
376: • Ubuntu is shipped in stable and regular release cycles; a new release will
380: • Ubuntu is entirely committed to the principles of open source software
В строках 9, 330, 337 и 359 присутствуют символы неразрывного пробела Unicode.
Конкретный результат, который вы можете получить, возможно, из-за grep
Поддержка UTF-8. Для локали Unicode некоторые из этих символов могут сравниваться с обычным символом ASCII. Форсирование языка C покажет ожидаемые результаты в этом случае:
$ LANG=C grep -Pn '[\x80-\xFF]' install.en.txt| head
9:Appendix F, GNU General Public License.
14:(codename "‘Xenial Xerus’"), for the 64-bit PC ("amd64") architecture. It also
18:━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
330:when things go wrong. The Installation Howto can be found in Appendix A,
337:Chapter 1. Welcome to Ubuntu
359:1.1. What is Ubuntu?
368: • Ubuntu will always be free of charge, and there is no extra fee for the "
372: • Ubuntu includes the very best in translations and accessibility
376: • Ubuntu is shipped in stable and regular release cycles; a new release will
380: • Ubuntu is entirely committed to the principles of open source software
$ LANG=en_GB.UTF-8 grep -Pn '[\x80-\xFF]' install.en.txt| head
9:Appendix F, GNU General Public License.
330:when things go wrong. The Installation Howto can be found in Appendix A,
337:Chapter 1. Welcome to Ubuntu
359:1.1. What is Ubuntu?
394:1.1.1. Sponsorship by Canonical
402:1.2. What is Debian?
456:1.2.1. Ubuntu and Debian
461:1.2.1.1. Package selection
475:1.2.1.2. Releases
501:1.2.1.3. Development community
Вы можете распечатать все не-ASCII строки файла, используя мой скрипт на Python 3, который я размещаю на GitHub здесь:
GitHub: ByteCommander / проверка кодировки
Вы можете клонировать или загрузить весь репозиторий или просто сохранить файл encoding-check
и сделать его исполняемым с помощью chmod +x encoding-check
,
Затем вы можете запустить его так, чтобы файл проверялся как единственный аргумент:
./encoding-check FILENAME
если он находится в вашем текущем рабочем каталоге, или.../path/to/encoding-check FILENAME
если он расположен в/path/to/
, или же...encoding-check FILENAME
если он расположен в каталоге, который является частью$PATH
переменная окружения, т.е./usr/local/bin
или же~/bin
,
Без каких-либо необязательных аргументов он будет печатать каждую строку и ее номер, где он нашел не-ASCII-символы. Наконец, есть итоговая строка, которая сообщает вам, сколько строк в файле было в общей сложности и сколько из них содержало не-ASCII-символы.
Этот метод гарантированно правильно декодирует все символы ASCII и обнаруживает все, что определенно не является ASCII.
Вот пример запуска файла, содержащего первые 20 строк вашего заданного install.en.txt
:
$ ./encoding-check install-first20.en.txt
9: Appendix��F, GNU General Public License.
14: (codename "���Xenial Xerus���"), for the 64-bit PC ("amd64") architecture. It also
18: ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
--------------------------------------------------------------------------------
20 lines in 'install-first20.en.txt', thereof 3 lines with non-ASCII characters.
Но в скрипте есть несколько дополнительных аргументов для настройки проверенной кодировки и формата вывода. Просмотрите справку и попробуйте их:
$ encoding-check -h
usage: encoding-check [-h] [-e ENCODING] [-s | -c | -l] [-m] [-w] [-n] [-f N]
[-t]
FILE [FILE ...]
Show all lines of a FILE containing characters that don't match the selected
ENCODING.
positional arguments:
FILE the file to be examined
optional arguments:
-h, --help show this help message and exit
-e ENCODING, --encoding ENCODING
file encoding to test (default 'ascii')
-s, --summary only print the summary
-c, --count only print the detected line count
-l, --lines only print the detected lines
-m, --only-matching hide files without matching lines from output
-w, --no-warnings hide warnings from output
-n, --no-numbers do not show line numbers in output
-f N, --fit-width N trim lines to N characters, or terminal width if N=0;
non-printable characters like tabs will be removed
-t, --title print title line above each file
Как --encoding
каждый кодек, который знает Python 3, действителен. Просто попробуйте один, в худшем случае вы получите небольшое сообщение об ошибке...
Эта команда Perl в основном заменяет grep
команда (не хватает цветов):
perl -ne '/[\x80-\xFF]/&&print($ARGV."($.):\t^".$_)' *.xml
n
: заставляет Perl принимать следующий цикл вокруг вашей программы, который заставляет его перебирать аргументы имени файла, вроде sed -n или awk:LINE: while (<>) { ... # your program goes here }
-e
: может использоваться для ввода одной строки программы./[\x80-\xFF]/&&print($ARGV."($.):\t^".$_)
: Если строка содержит символ в диапазоне\x80-\xFF
, печатает имя текущего файла, номер строки текущего файла,:\t^
строка и содержимое текущей строки.
Выведите в каталог образцов, содержащий образец файла в вопросе и файл, содержащий только ààààà
и символ новой строки:
% perl -ne '/[\x80-\xFF]/&&print($ARGV."($.):\t^".$_)' file | head -n 10
file(9): ^Appendix F, GNU General Public License.
file(14): ^(codename "‘Xenial Xerus’"), for the 64-bit PC ("amd64") architecture. It also
file(18): ^â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”â”
file(330): ^when things go wrong. The Installation Howto can be found in Appendix A,
file(337): ^Chapter 1. Welcome to Ubuntu
file(359): ^1.1. What is Ubuntu?
file(368): ^ • Ubuntu will always be free of charge, and there is no extra fee for the "
file(372): ^ • Ubuntu includes the very best in translations and accessibility
file(376): ^ • Ubuntu is shipped in stable and regular release cycles; a new release will
file(380): ^ • Ubuntu is entirely committed to the principles of open source software
% perl -ne '/[\x80-\xFF]/&&print($ARGV."($.):\t^".$_)' file1
file1(1): ^ààààà