代码之家  ›  专栏  ›  技术社区  ›  JR Lawhorne

如何将子目录中的文件与unix find execute和cat连接到单个文件中?

  •  9
  • JR Lawhorne  · 技术社区  · 16 年前

    我能做到这一点:

    $ 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 {} \;
    

    为什么不呢?

    8 回复  |  直到 16 年前
        1
  •  28
  •   Commodore Jaeger    16 年前

    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
    
        2
  •  5
  •   Johnny A    16 年前

    隐马尔可夫模型。。。当您将out.txt输出到当前目录时,find似乎正在递归。

    尝试一下

    find . -type f -exec cat {} \; > ../out.txt
    
        3
  •  3
  •   JoMo    16 年前

    你可以这样做:

    $ cat `find . -type f` > out.txt
    
        4
  •  2
  •   Jay    16 年前

    只需将find的输出重定向到一个文件中,因为您只需要将所有文件都分类到一个大文件中:

    find . -type f -exec cat {} \; > /tmp/out.txt
    
        5
  •  1
  •   dlamblin    16 年前

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

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

    所以你在给予 find 这些论点: "." "-type" "f" "-exec" "cat" 你给重定向这些参数: "out.txt" "{}" ";" . 这混淆了 找到 不终止 -exec 带有分号且不使用文件名作为参数(“”)的参数也可能混淆重定向。

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

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

    现在,如果您真的只有一个级别的子目录和普通文件,那么您可以做一些愚蠢和简单的事情,比如:

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

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

        6
  •  0
  •   Zsolt Botykai    16 年前

    或者,如果你使用真正伟大的z shell,那就把那些无用的发现忽略掉。( zsh ,您可以这样做:

    setopt extendedglob
    

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

    cat **/*(.) > outfile 
    

    只是工作:

        7
  •  0
  •   Milan BabuÅ¡kov    16 年前

    试试这个:

    (find . -type f -exec cat {} \;) > out.txt 
    
        8
  •  0
  •   Mark    16 年前

    在巴什你可以做

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

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