How do I manage files with spaces and newlines when using find on linux?



  • Also see:
    Man page for find.
    Man page for xargs.

    When you passing the output of find to another command, some filenames have spaces and newlines. Using the right find options can help produce the correct results.

    Out find directory contains the following. One file has spaces.

    $ ls
     biff      bigfile2   fileb   int   'Users on system'
     bigfile   filea      filex   test
    

    We are looking for a word in one of the files. A normal find produces this output. The file "Users on systems", is taken as three separate files because of the spaces.

    $ find . -type f -print | xargs grep Perm
    grep: ./Users: No such file or directory
    grep: on: No such file or directory
    grep: system: No such file or directory
    

    Now add -print0 and -0 to xargs. It grep found a match in our file with spaces.

    $ find . -type f -print0 | xargs -0 grep Perm
    ./Users on system:Permissions are here.
    
           -print0
                  True; print the full file name on the standard output,  followed
                  by  a  null  character  (instead  of  the newline character that
                  -print uses).  This allows file names that contain  newlines  or
                  other  types  of white space to be correctly interpreted by pro‐
                  grams that process the find output.  This option corresponds  to
                  the -0 option of xargs.
    
           -0, --null
                  Input items are terminated by a null  character  instead  of  by
                  whitespace,  and the quotes and backslash are not special (every
                  character is taken literally).  Disables the end of file string,
                  which  is  treated  like  any other argument.  Useful when input
                  items might contain white space, quote  marks,  or  backslashes.
                  The  GNU  find  -print0  option produces input suitable for this
                  mode.
    


© Lightnetics 2022