9

我可以做这个:

$ find .
.
./b
./b/foo
./c
./c/foo

还有这个:

$ find . -type f -exec cat {} \;
This is in b.
This is in c.

但不是这个:

$ find . -type f -exec cat > out.txt {} \;

为什么不?

4

8 回答 8

29

find 的 -exec 参数为它找到的每个文件运行一次您指定的命令。尝试:

$ find . -type f -exec cat {} \; > out.txt

或者:

$ find . -type f | xargs cat > out.txt

xargs 将其标准输入转换为您指定的命令的命令行参数。如果您担心文件名中的嵌入空格,请尝试:

$ find . -type f -print0 | xargs -0 cat > out.txt
于 2008-10-03T19:50:08.627 回答
5

嗯......当您将 out.txt 输出到当前目录时,find 似乎正在递归

尝试类似的东西

find . -type f -exec cat {} \; > ../out.txt
于 2008-10-03T20:12:53.683 回答
3

你可以做这样的事情:

$ cat `find . -type f` > out.txt
于 2008-10-03T19:53:39.870 回答
2

将 find 的输出重定向到一个文件怎么样,因为您要做的就是将所有文件放入一个大文件中:

find . -type f -exec cat {} \; > /tmp/out.txt
于 2008-10-03T19:52:02.617 回答
1

也许您已经从其他响应中推断出>符号在 find 将其作为参数之前由 shell 解释。但是要回答您的“为什么不”,让我们看看您的命令,即:

$ find . -type f -exec cat > out.txt {} \;

所以你给出了find这些论点:"." "-type" "f" "-exec" "cat"你给出了重定向这些论点:"out.txt" "{}"";". 这会混淆不以分号find结尾的参数并且不使用文件名作为参数(“{}”),它也可能会混淆重定向。-exec

查看其他建议,您应该真正避免在您找到的同一目录中创建输出。但他们会考虑到这一点。这种-print0 | xargs -0组合非常有用。你想输入的可能更像是:

$ find . -type f -exec cat \{} \; > /tmp/out.txt

现在如果你真的只有一级子目录和普通文件,你可以做一些愚蠢而简单的事情:

cat `ls -p|sed 's/\/$/\/*/'` > /tmp/out.txt

它将ls列出所有附加到目录的文件和目录'/',同时sed将 a 附加'*'到目录。然后 shell 将解释这个列表并展开 glob。假设这不会导致 shell 处理太多文件,这些都将作为参数传递给 cat,并且输出将写入 out.txt。

于 2008-10-03T20:28:16.430 回答
0

或者,如果您使用非常棒的 Z shell ( zsh),则忽略无用的 find ,您可以这样做:

setopt extendedglob

(这应该在你的.zshrc)然后:

cat **/*(.) > outfile 

只是工作:-)

于 2008-10-03T19:58:50.437 回答
0

试试这个:

(find . -type f -exec cat {} \;) > out.txt 
于 2008-10-03T20:35:38.210 回答
0

在 bash 你可以做

cat $(find . -type f) > out.txt

使用 $( ) 您可以从命令获取输出并将其传递给另一个

于 2008-10-03T21:29:49.520 回答