如何grep特殊字符NUL(^@^@^@)

34 linux unix

文件:

O000000667520994000000074720121112000000N^@^@^@ 
Run Code Online (Sandbox Code Playgroud)

我使用了下面的命令,但它不起作用。

grep "^@^@^@" *
Run Code Online (Sandbox Code Playgroud)

小智 62

您可以通过其十六进制代码 grep 任何字符,包括 perl-regexp 模式 (-P) 中的控制/不可打印字符:

grep -Pa '\x00' ...
Run Code Online (Sandbox Code Playgroud)


Joh*_*man 15

^@不是克拉^和 at 符号@,它是一个字符。这就是一些程序显示 NUL 字符的方式——ASCII 值 0,\0在 C 中也称为。

在这里,我创建了一个包含 NUL 字节的文件。请注意,我cat -v用来显示非打印字符。

$ cat -v blah
hello
null^@
hi
$ hexdump -C blah
00000000  68 65 6c 6c 6f 0a 6e 75  6c 6c 00 0a 68 69 0a     |hello.null..hi.|
0000000f
Run Code Online (Sandbox Code Playgroud)

Grep 很难找到 NUL,因为它们用于终止 C 中的字符串。 然而,Sed 可以完成这项工作:

$ sed -n '/\x0/p' blah
null
$ sed -n '/\x0/p' blah | cat -v
null^@
Run Code Online (Sandbox Code Playgroud)

在 vi 中,在插入模式下按Ctrl- VCtrl- Shift-@插入空字节。


rob*_*nst 6

如果grep -P不起作用(例如在 OS X 上),请尝试以下操作:

grep -E '\x00' ...
Run Code Online (Sandbox Code Playgroud)

  • 此答案适用于 BSD grep,请尝试 GNU grep 的最佳答案:`grep -Pa '\x00' ...` (4认同)

小智 -3

字符 ^@ 是 NUL 字符,所以恐怕无法直接对其进行 grep。

您最好的选择可能是编写一个简单的程序来搜索该字节序列。

或者,您可以尝试将其转换为某种形式的十六进制转储(odxxd)并 grep 到其输出中。但坦率地说,要做到正确是很困难的。