43

File:

O000000667520994000000074720121112000000N^@^@^@ 

I used the below command but it doesn't work.

grep "^@^@^@" *
0

5 Answers 5

74

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

grep -Pa '\x00' ...
4
  • I can't find a way to check if file contains only ASCII=0 bytes... grep -Pv '\x00' file does not work in Cygwin...
    – pbies
    Aug 16, 2018 at 12:51
  • 1
    @mpy Without -a (sometimes?) it doesn't even find the pattern. Thanks! Might help @pbies as well. Nov 21, 2019 at 8:10
  • but you might not see them, pipe to | cat -v
    – CervEd
    Dec 18, 2021 at 22:54
  • 1
    Mac grep doesn't support -P unfortunately. :( Oct 10, 2023 at 20:23
16

^@ 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.

1
  • † In vi, to find a null character, press / to start searching and then Ctrl-V, Ctrl-Shift-@ to insert a null byte, and then ENTER. Then use Next and Previous to show found instances.
    – diamondsea
    May 25, 2022 at 13:36
10

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

grep -E '\x00' ...
2
  • 1
    Are you sure that this works? I does not with my version: grep (GNU grep) 2.14
    – guettli
    Nov 20, 2017 at 7:19
  • 4
    This answer is for BSD grep, try the top answer for GNU grep: grep -Pa '\x00' ...
    – robinst
    Nov 22, 2017 at 3:18
1

In bash you can add special characters when prefixed with C-q or C-v. So you can, for example

grep 'Ctrl-vCtrl-a' file.txt

The search string should be read as control key + character v, followed by control key + character a, which searches for ASCII value SOH (01). Unfortunately this doesn't work for the NUL character.

0
-3

Character ^@ is the NUL char, so I'm afraid that it cannot be grepped directly.

Your best option would be probably to write a simple program that searches for this sequence of bytes.

Alternatively you may try to convert it into some form of hexadecimal dump (od, xxd or so) and grep into the output of it. But frankly speaking, it would be tricky to get it right.

You must log in to answer this question.