Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

share|improve this question
    
In GNU sed, yes, but note that on many unices, text utilities are not capable of handling null bytes. –  Gilles Apr 19 '12 at 1:04

2 Answers 2

up vote 6 down vote accepted

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.

share|improve this answer
2  
You can echo -ne \\0 to avoid a newline. –  l0b0 Apr 18 '12 at 10:42
    
Replace hexdump -C with uniname -bcepu to see which character it dumps. –  l0b0 Apr 18 '12 at 10:43
3  
It should be mentioned that \x is a non-standard sed extension, but GNU sed does provide it. –  jw013 Apr 18 '12 at 12:08
2  
It should be also mentioned, that echo -e is a bashism. printf is much more compatible. –  jofel Apr 18 '12 at 12:09

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
$  
share|improve this answer
    
@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... –  jofel Apr 18 '12 at 12:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.