gpt4 book ai didi

linux - 查找包含非打印字符(空字节)的文件

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:43:50 25 4
gpt4 key购买 nike

我的应用程序日志中有一个包含奇怪字符的字段。我仅在使用 less 命令时才看到这些字符。

我试图将我的代码行的结果复制到一个文本文件中,我看到的是

CTP_OUT=^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@

我想知道是否有办法找到这些空字符。我尝试使用 grep 命令,但它没有显示任何内容

最佳答案

我简直不敢相信,我可能会写一个涉及cat的答案!

您观察到的字符是不可打印 字符,通常写在Carret notation 中.字符的 Caret 符号是一种可视化不可打印字符的方法。如 OP 中所述,^@NULL 的表示。

如果您的文件包含不可打印的字符,您可以使用 cat -vET 可视化它们:

-E, --show-ends: display $ at end of each line
-T, --show-tabs: display TAB characters as ^I
-v, --show-nonprinting: use ^ and M- notation, except for LFD and TAB

source: man cat

我已经向它添加了 -E-T 标志,以转换所有不可打印的内容。

由于 grep 本身不会以任何形式输出不可打印的字符,因此您必须将其输出通过管道传输到 cat 才能看到它们。以下示例显示所有包含不可打印字符的行

显示所有包含不可打印字符的行:

$ grep -E '[^[:print:]]' --color=never file | cat -vET

在这里,ERE [^[:print:]] 选择所有不可打印的字符。

显示所有带有NULL的行:

$ grep -Pa '\x00' --color=never file | cat -vET

请注意,我们需要在此处使用 Perl 正则表达式,因为它们理解十六进制和八进制表示法。

Various control characters can be written in C language style: \n matches a newline, \t a tab, \r a carriage return, \f a form feed, etc.

More generally, \nnn, where nnn is a string of three octal digits, matches the character whose native code point is nnn. You can easily run into trouble if you don't have exactly three digits. So always use three, or since Perl 5.14, you can use \o{...} to specify any number of octal digits.

Similarly, \xnn, where nn are hexadecimal digits, matches the character whose native ordinal is nn. Again, not using exactly two digits is a recipe for disaster, but you can use \x{...} to specify any number of hex digits.

source: Perl 5 version 26.1 documentation

一个例子:

$ printf 'foo\012\011\011bar\014\010\012foobar\012\011\000\013\000car\012\011\011\011\012' > test.txt
$ cat test.txt
foo
bar

foobar

car

如果我们现在单独使用 grep,我们会得到以下结果:

$ grep -Pa '\x00' --color=never test.txt

car

但是通过管道将它传递给 cat 可以让我们可视化控制字符:

$ grep -Pa '\x00' --color=never test.txt | cat -vET
^I^@^K^@car$

为什么 --color=never:如果你的 grep 被调整为具有 --color=auto--color =always 它将添加额外的控制字符以解释为终端的颜色。这可能会使您对内容感到困惑。

$ grep -Pa '\x00' --color=always test.txt | cat -vET
^I^[[01;31m^[[K^@^[[m^[[K^K^[[01;31m^[[K^@^[[m^[[Kcar$

关于linux - 查找包含非打印字符(空字节)的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54131197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com