0

是否有任何 linux 命令行工具可以对可能与 UTF-8 字符串和不可打印字符混合的任何文件内容进行分类,但也将不可打印字符显示为 \xNN?

比如abc\xa1defg

PS:我不需要像 xxd 产生的两列输出,或者产生的空格分隔输出od

到目前为止,最接近的结果是: od -t c FILE

0000000   S   Q   L   i   t   e       f   o   r   m   a   t       3  \0
0000020 020  \0  \n   \t \0  \0  \0  \0  \0  \0  \0 001  \0  \0  \0 004
0000040  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0 001  \0  \0  \0 004

但我想要的是这样

SQLite format 3\0\020\0
       \0\0.....

发现了一个类似的问题:https ://unix.stackexchange.com/questions/176111/how-to-dump-a-binary-file-as-acc-string-literal

4

1 回答 1

1

不完美,但在附近:

hexdump -e '16 "%_c" "\n"' file.sqlite

-e指定输出格式,16= 每行的字符数(迭代计数),_c参见手册页:

以默认字符集输出字符。非打印字符以三个字符显示,零填充八进制,除了那些可以用标准转义符号(见上文)表示的字符,它们显示为两个字符串。

输出:

SQLite format 3\0
200\0001001\0@  \0\0006�\0\0\0\a



如果您真的想要问题中描述的输出,则必须推出自己的程序。这是一个快速简便的解决方案:

#!/usr/bin/env python3
import sys

if len(sys.argv) < 2:
    exit(1)

with open(sys.argv[1], "rb") as f:
    while True:
        b = f.read(1)
        if not b:
            break
        c = ord(b)
        print(f'\\x{c:02x}' if (c < 32 or c > 126 and c < 161) else f'{c:c}', end='')

用这两条线生成的测试文件

with open('test.dat','wb')as f:
    f.write(bytearray([i for i in range(256)]))

的输出myhexdump test.dat将是:

\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ
于 2019-07-16T18:49:23.553 回答