Search code examples
bashfindtailxargs

xargs or tail gives error with spaces in directory names


I have a directory structure

Dir 1
Dir 2
Dir 3

, so each of the directory names contains a space.

Each directory contains the file batch_output.txt. Each of these files starts with a header line and then the data on the next lines.

I want to append these data files, and the header one time at the top (so the header should only be extracted from the first file, and not repeatedly) . The command

find . -name batch_output.txt -type f

returns the paths of the batch_output.txt files just fine, but my attempt to append the data by means of the command

find . -name batch_output.txt -type f | xargs -n 1 tail -n +2

gives me the errors

tail: cannot open ‘./Dir’ for reading: No such file or directory
tail: cannot open ‘1/batch_output.txt’ for reading: No such file or directory
tail: cannot open ‘./Dir’ for reading: No such file or directory
tail: cannot open ‘2/batch_output.txt’ for reading: No such file or directory
tail: cannot open ‘./Dir’ for reading: No such file or directory
tail: cannot open ‘3/batch_output.txt’ for reading: No such file or directory

I think tail has a problem with the spaces in the directory names.

Under the condition that I have to retain the spaces in the directory names, how do I solve this problem?


Solution

  • Try -print0 option with -0 option in xargs:

    find . -name batch_output.txt -type f -print0 | xargs -0 -n 1 tail -n +2
    

    As per man find:

    -print0
      This primary always evaluates to true. It prints the pathname of the current file 
      to standard output, followed  by an ASCII NUL character (character code 0).