Home > Fixes, HowTo's > Converting Null

Converting Null

April 24th, 2009 Leave a comment Go to comments

Simple shell script fix this week – convert all newlines to null characters.

Since most Linux shells have a major problem with doing this in a sensible way, the following (on my box called simply ‘0’) takes any input (either from files or via a pipe) and converts the characters.

1
2
3
4
5
6
7
#!/usr/bin/perl
# From: http://hash-bang.net/2009/04/converting-nullconverting-null/
# Author: Matt Carter <m@ttcarter.com>
while (<>) {
	s/\n/\x00/g;
	print;
}

So now commands like:

find -type f | 0 | xargs -0 | mplayer

work perfectly (in the above case to play all files in directories recursively.

You may well ask why I don’t use the simple ‘-print0′ argument for the find program – because it doesn’t work when using later pipes.

For example if i wanted to sort the above, ‘sort’ would see the null symbol as a regular character.

So ‘0’ works nicely in this case:

find -type f | 0 | sort | xargs -0 | mplayer

Or even:

find -type f | 0 | shuffle | xargs -0 | mplayer

To play all files recursively, in random order. See the article on shuffle for the source code of that filter.

Categories: Fixes, HowTo's Tags: , , ,
  1. sma
    April 3rd, 2010 at 09:19 | #1

    Hm, instead of “find -type f | 0 | cmd | …” you obviously meant “find -type f | cmd | 0 | …”.

    • April 6th, 2010 at 10:45 | #2

      Depends what you are doing I suppose. I was assuming ‘cmd’ would be something like ‘xargs -0′ as so:
      find -type f | 0 | xargs -0 echo
      Which works exactly the same as:
      find -type f -print0 | xargs -0 echo
      I guess it depends on what the command is and how nicely it can process null characters. ‘0’ was originally designed so that programs that do not understand null terminated arguments can work. A good example would be:
      ls -1 | 0 | xargs -0 echo
      Where poor ‘ls’ cannot understand null terminated file names and thus would fail on any file name containing whitespace.

  1. No trackbacks yet.
*