22

Related to another question, in order to fuzzily detect binary files, is there a way to detect ␀ bytes in sed?

1
  • In GNU sed, yes, but note that on many unices, text utilities are not capable of handling null bytes. Commented Apr 19, 2012 at 1:04

2 Answers 2

24

Example:

Prove I'm sending a NUL byte, followed by a newline:

$ echo -e \\0 | hexdump -C
00000000  00 0a                                             |..|
00000002

Now I change the NUL byte to an ! exclamation mark:

$ echo -e \\0 | sed 's/\x00/!/' | hexdump -C
00000000  21 0a                                             |!.|

So the trick is using \x00 as NUL-byte.

4
  • 3
    You can echo -ne \\0 to avoid a newline. Commented Apr 18, 2012 at 10:42
  • Replace hexdump -C with uniname -bcepu to see which character it dumps. Commented Apr 18, 2012 at 10:43
  • 7
    It should be mentioned that \x is a non-standard sed extension, but GNU sed does provide it. Commented Apr 18, 2012 at 12:08
  • 6
    It should be also mentioned, that echo -e is a bashism. printf is much more compatible. Commented Apr 18, 2012 at 12:09
10

Yes, the pattern \x00 matches to the null byte.

Example:

$ printf "\0\n\0\n" > file
$ sed -e 's/\x00/test/' -i file
$ cat file
test
test
$  
1
  • 1
    @l0b0: The reason, why it worked for me, was that I used zsh. According to POSIX, it replaces \0 by the zero byte. This replacement is not necessary ("shall be supported"), and actually bash does not support it directly. For it, you need to use echo -e. I replace echo with with printf in my answer which seems to be more compatible... Commented Apr 18, 2012 at 12:04

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.