我可以做这个:
$ 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 {} \;
为什么不?
我可以做这个:
$ 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 {} \;
为什么不?
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
嗯......当您将 out.txt 输出到当前目录时,find 似乎正在递归
尝试类似的东西
find . -type f -exec cat {} \; > ../out.txt
你可以做这样的事情:
$ cat `find . -type f` > out.txt
将 find 的输出重定向到一个文件怎么样,因为您要做的就是将所有文件放入一个大文件中:
find . -type f -exec cat {} \; > /tmp/out.txt
也许您已经从其他响应中推断出>
符号在 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。
或者,如果您使用非常棒的 Z shell ( zsh
),则忽略无用的 find ,您可以这样做:
setopt extendedglob
(这应该在你的.zshrc
)然后:
cat **/*(.) > outfile
只是工作:-)
试试这个:
(find . -type f -exec cat {} \;) > out.txt
在 bash 你可以做
cat $(find . -type f) > out.txt
使用 $( ) 您可以从命令获取输出并将其传递给另一个