How to grep for special character NUL (^@^@^@)

You can grep for any characters including control/non-printable characters in perl-regexp mode (-P) by its hex code:

grep -Pa '\x00' ...

^@ is not a carat ^ and at-sign @, it's one character. It's how some programs display the NUL character—ASCII value 0, also known as \0 in C.

Here I've created a file with a NUL byte in it. Notice that I use cat -v to show non-printing characters.

$ 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

Grep has trouble finding NULs since they're used to terminate strings in C. Sed, however, can do the job:

$ sed -n '/\x0/p' blah
null
$ sed -n '/\x0/p' blah | cat -v
null^@

In vi, in insert mode press Ctrl-V, Ctrl-Shift-@ to insert a null byte.


If grep -P doesn't work (e.g. on OS X), try this:

grep -E '\x00' ...