【问题标题】:How to pass hundreds of files from multiple subdirectories to cat?如何将数百个文件从多个子目录传递给 cat?
【发布时间】:2011-12-06 23:41:34
【问题描述】:

我有一个充满子目录的目录,每个子目录中都有一些文本文件(即深度为 1)。

我想将所有这些文件(不分先后)合并到一个文件中:

cat file1 file2.... fileN >new.txt

是否有一个 bash shell 单行程序可以列出这些目录中的所有文件并将它们传递给 cat?

【问题讨论】:

    标签: linux bash unix


    【解决方案1】:

    这个怎么样?

    find . -name '*.txt' -exec cat {} \; > concatenated.txt
    

    当然它会多次调用 cat 而不是一次,但效果是一样的。

    【讨论】:

    • 您可以使用加号代替分号:-exec cat {} +。这只会使用所有参数调用cat 一次——就像xargs 一样。不过,我更喜欢xargs,因为它非常灵活。
    【解决方案2】:
    find . -type f -print0 | xargs -0 cat
    

    find 将递归搜索文件 (-type f) 并将其名称打印为以空字符结尾的字符串 (-print0)。

    xargs 将从标准输入读取以空字符结尾的字符串 (-0) 并将它们作为参数传递给 cat

    【讨论】:

    • @userunknown:没用怎么办?并非所有版本的find 都支持-exec command {} +
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    相关资源
    最近更新 更多