【问题标题】:Reading files from child directories of path and appending them to one file从路径的子目录中读取文件并将它们附加到一个文件中
【发布时间】:2017-06-23 13:01:21
【问题描述】:

我有一个包含 20 个子文件夹的文件夹,每个子文件夹都包含一个文件。我想从子文件夹中读取所有 20 个文件并将它们附加到另一个文件中。 我该怎么办?有没有这方面的 awk 命令? python/perl 脚本或 linux 命令都会非常有用

【问题讨论】:

  • 这在几乎任何语言中都非常可行。我建议你把这一切分成几个步骤,并弄清楚如何用你选择的语言来做这些事情。根据您列出的内容,我建议在 Python 中进行。写起来会更容易。
  • 用windows shell 超级简单,linux 也应该有。恕我直言,Python 太过分了。
  • 我不同意 Python 的过度杀伤力,但是是的,它在任何事情上都是可行/容易的。
  • cat file1 file2 file3 > dest_file

标签: linux shell


【解决方案1】:

最简单的方法可能是(除非您需要比文件内容更多的信息):

cat <directory>/*/* >> <resulting_file>

【讨论】:

  • 我讨厌这种答案。没有合适的例子,新手只会迷失自己。最好用一个真实的例子来格式化答案,以这种方式:Let's assume we have a folder at path : D:\my_folder, which has 2 folders, 2 files... blah, blah... For this folder, to get the desired result, the command would be : cat D:\my_folder ...
【解决方案2】:

使用 find 命令,您可以使用它来限制目录路径/文件类型、修改时间等。 find 命令用于默认递归搜索(即它从目录开始直到树的最后一个子节点。

在您的情况下,我假设您正在寻找任何文件。你可以这样做。

find <PATH from where to search> -type f > log file # adding filters that you are looking for files.
Ex: find /users/hero/parent -type f > listoffiles.log

如果您正在寻找任何特定类型的文件,例如日志文件(或)c 文件等,您可以添加如下过滤器。

find /path -type f -name *.log > listoflogfiles

注意:默认情况下,find 是递归搜索。 希望这会有所帮助:)

【讨论】:

    【解决方案3】:

    使用 python(3) 可以使用以下代码: 它首先打开新的 target_file,然后打开每个 source_file 并将其内容写入 target_file。

    import os
    
    path_with_subdirs = '/dir/with/subdirectories'
    
    source_files = [os.path.join(dp, f) for dp, dn, filenames in os.walk(path_with_subdirs) for f in filenames]
    
    target_file = '/target/location/output_file.txt'
    
    with open(target_file, 'w') as target:
        for source_file in source_files:
            with open(source_file, 'r') as source:
                [target.write(line) for line in source]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-02
      • 2019-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多