如何使用Unix将子目录中的文件连接起来,找到execute并将cat合并为一个文件?
时间:2020-03-06 15:05:36 来源:igfitidea点击:
我可以做这个:
$ 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
如何将find的输出重定向到一个文件中,因为我们要做的只是将所有文件分类为一个大文件:
find . -type f -exec cat {} \; > /tmp/out.txt
你可以做这样的事情:
$ cat `find . -type f` > out.txt
或者,如果使用真正出色的Z壳(zsh
),则忽略掉没有用的查找,可以执行以下操作:
setopt extendedglob
(这应该在.zshrc中)
然后:
cat **/*(.) > outfile
才有效:-)
嗯...当我们将out.txt输出到当前目录时,查找似乎正在递归
尝试类似的东西
find . -type f -exec cat {} \; > ../out.txt
也许我们从其他响应中推断出,在find将其>作为参数之前,shell已解释了>
符号。但是要回答"为什么不这样做",请看一下命令:
$ find . -type f -exec cat > out.txt {} \;
因此,我们要给"查找"这些参数:""。 " -type"" f"" -exec"" cat",我们要给这些重定向参数:"" out.txt"" {}"
和";"
。通过不以分号终止-exec
参数以及不使用文件名作为参数(" {}")来混淆" find",这也可能使重定向混淆。
查看其他建议,我们实际上应该避免在找到的相同目录中创建输出。但是,考虑到它们,它们会起作用。和-print0 | xargs -0
组合非常有用。我们想要输入的内容可能更像是:
$ find . -type f -exec cat \{} \; > /tmp/out.txt
现在,如果我们实际上只有一个子目录层并且只有普通文件,则可以执行以下愚蠢而简单的操作:
cat `ls -p|sed 's/\/$/\/*/'` > /tmp/out.txt
这使ls
列出所有文件和目录,并在目录后添加'/',而sed
将在目录后添加'*'。然后,shell将解释此列表并扩展glob。假设不会导致shell需要处理的文件过多,则这些文件将全部作为参数传递给cat,并且输出将被写入out.txt。
试试这个:
(find . -type f -exec cat {} \;) > out.txt
用bash你可以做
cat $(find . -type f) > out.txt
使用$(),我们可以从命令获取输出并将其传递给另一个