How to make grep separate output by NULL characters? How to make grep separate output by NULL characters? unix unix

How to make grep separate output by NULL characters?


So I filed this issue as a feature request in the GNU grep bug mailing list, and it appeared to be a bug in the code.

It has been fixed and pushed to master, so it will be available in the next release of GNU grep: http://git.savannah.gnu.org/cgit/grep.git/commit/?id=cce2fd5520bba35cf9b264de2f1b6131304f19d2

To summarize: this patch makes sure that the -z flag not only works in conjunction with -l, but also with -o.


What comes into my mind would be to use a group separator, for example something like:

grep -rzPIho '}\n\n\w\w\b' $FILE -H | sed "s/^$FILE:/\x0/"


Here is another way to do this, which should be more foolproof than what @bufh posted, but which is also more complicated and slower.

$ grep -rIZl '' --include='*.pl'| xargs -0 cat | dos2unix | tr '\n\0' '\0\n' \      | grep -Pao '}\x00\x00\w\w\b' | tr '\0\n' '\n\0' | od -a

The dos2unix is obviously only needed when working with windows line endings. So the punchline here is that we swap null bytes with newlines in the input, have grep match on nullbytes instead and swap things back.

0000000   }  nl  nl   m   y  nul   }  nl  nl   i   f  nul   }  nl  nl   m0000020   y  nul   }  nl  nl   m   y  nul   }  nl  nl   i   f  nul   }  nl0000040  nl   m   y  nul0000044