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 open1/batch_output.txt’ for reading: No such file or directory
tail: cannot open ‘./Dir’ for reading: No such file or directory
tail: cannot open2/batch_output.txt’ for reading: No such file or directory
tail: cannot open ‘./Dir’ for reading: No such file or directory
tail: cannot open3/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?

+3


source to share


4 answers


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).

      

+3


source


Use an argument -exec

for find

:

find . -name batch_output.txt -type f -exec tail -n +2 {} \;

      



If you want to put the output in a new file, just redirect it:

find . -name batch_output.txt -type f -exec tail -n +2 {} \; > /path/to/outfile

      

+1


source


He tail

who does not receive any quoted filenames. Use an argument -I

for xargs:

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

      

0


source


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

      

0


source







All Articles