2011-09-19

Print a NUL-terminated string with awk

I thought it would have been easier to print a NUL-terminated string in awk (mawk as it's the default in Debian), but after some trial-and-fail I was able to come up with this kinda ugly solution:


$ echo -e "123\n456" | awk 'BEGIN { ORS="" } { print $0 ; printf("%c", "") }'  | xargs -n1 -0 echo 
123
456

That:

  • set the Output Records Separator (ORS) to the empty string (default is the \n, new line)
  • print the input line (do your elaboration there, if you need)
  • print the null character, as explained in the mawk manpage: "mawk cannot handle ascii NUL \0 in the source or data files.  You can output NUL using printf with %c, and any other 8 bit character is acceptable input."
  • show that it's actually emitting NUL-terminated strings
There's really no better way to do that?

1 comment:

Jeroen Schot said...

You should use 0 instead of "" for the null character, the latter does not work in original-awk.

I would go for the awk code { printf "%s%c", $0, 0 }.

If you are only interested in gawk you can just set ORS="\0".