Xargs or tail gives error with spaces in directory names
I have a directory structure
Dir 1
Dir 2
Dir 3
therefore, each of the directory names contains a space.
Each directory contains a file batch_output.txt
. Each of these files starts with a header line and then data on the following lines.
I want to add these data files, and the header is once at the top (so the header should only be fetched from the first file, not reused). Command
find . -name batch_output.txt -type f
returns file paths batch_output.txt
just fine, but my attempt to add data using the command
find . -name batch_output.txt -type f | xargs -n 1 tail -n +2
gives me 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 the tail has a problem with spaces in directory names.
Assuming I have to preserve spaces in directory names, how do I solve this problem?
source to share
Try -print0
with option -0
in xargs
:
find . -name batch_output.txt -type f -print0 | xargs -0 -n 1 tail -n +2
By 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).
source to share
I believe the following script works enough.
#!/bin/bash
clear
clear
# Extract first line from the first hit by 'find'.
find . -name batch_output.txt -type f -print0 -quit | xargs -0 -n 1 head -n 1 > output.txt
# Append all the data after the first line.
find . -name batch_output.txt -type f -print0 | xargs -0 -n 1 tail -n +2 >> output.txt
source to share