Search code examples
fileunixnullcutnul

How to 'cut' on null?


Unix 'file' command has a -0 option to output a null character after a filename. This is supposedly good for using with 'cut'.

From man file:

-0, --print0
         Output a null character ‘\0’ after the end of the filename. Nice
         to cut(1) the output. This does not affect the separator which is
         still printed.

(Note, on my Linux, the '-F' separator is NOT printed - which makes more sense to me.)

How can you use 'cut' to extract a filename from output of 'file'?

This is what I want to do:

find . "*" -type f | file -n0iNf - | cut -d<null> -f1

where <null> is the NUL character.

Well, that is what I am trying to do, what I want to do is get all file names from a directory tree that have a particular MIME type. I use a grep (not shown).

I want to handle all legal file names and not get stuck on file names with colons, for example, in their name. Hence, NUL would be excellent.

I guess non-cut solutions are fine too, but I hate to give up on a simple idea.


Solution

  • Just specify an empty delimiter:

    cut -d '' -f1
    

    Notes:

    • The space between the -d and the '' is important, so that the -d and the empty string get passed as separate arguments; if you write -d'', then that will get passed as just -d, and then cut will think you're trying to use -f1 as the delimiter, which it will complain about, with an error message that "the delimiter must be a single character".
    • Per the comments to this answer, there are some systems where cut doesn't support using the null character as the delimiter. Fortunately, other answers on this page provide solutions that should work on such systems.