xargs 或 tail 给出错误,目录名称中有空格

xargs or tail gives error with spaces in directory names

我有一个目录结构

Dir 1
Dir 2
Dir 3

,所以每个目录名都包含一个space.

每个目录包含文件batch_output.txt。这些文件中的每一个都以 header 行开头,然后是下一行的数据。

我想追加这些数据文件,header一次在顶部(所以header应该只从第一个提取文件,而不是重复)。命令

find . -name batch_output.txt -type f

returns batch_output.txt 文件的路径很好,但我试图通过命令

附加数据
find . -name batch_output.txt -type f | xargs -n 1 tail -n +2

给我错误

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

我认为 tail 目录名称中的 space 有问题。

在必须保留目录名中的space的情况下,如何解决这个问题?

尝试 -print0 选项和 xargs 中的 -0 选项:

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

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

find使用-exec参数:

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

如果你想把输出放到一个新文件中,只需重定向它:

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

tail 没有得到单引号文件名。对 xargs:

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

我相信以下脚本足够有效。

#!/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