【问题标题】:Bash Mac Terminal to Organize Filestructure用于组织文件结构的 Bash Mac 终端
【发布时间】:2017-05-29 00:08:13
【问题描述】:

我有 12,000 多个文件需要整理。包含所有文件夹,但文件现在处于扁平文件结构中。

我的文件夹和文件都以它们应该所在的路径命名。例如,在一个目录中,我有一个名为 \textures 的文件夹和另一个名为 \textures\actors\bear 的文件夹,但是没有 \textures\actors 文件夹。我正在努力开发一个宏,该宏将获取这些文件夹并将它们放在每个文件夹和文件名建议它应该位于的正确位置。我希望能够自动将它们分类到textures,里面就是@ 987654325@,里面是bear。但是,有超过 12,000 个文件,所以我正在寻找一个自动化的过程来确定所有这些,并尽可能地执行它。

是否有一个脚本可以查看每个文件或文件夹名称并检测文件或文件夹应该在目录中的哪个文件夹并自动将它们移动到那里以及创建任何不存在于给定路径中的文件夹需要吗?

谢谢

【问题讨论】:

  • 德文,如果下面的解决方案有效,你能告诉我吗?也许通过投票来回答。
  • Devin,此解决方案是否有效,或者您需要帮助以实现您的目标?
  • 为什么目录名中有反斜杠?
  • 你能展示一个你的树结构的可视化例子吗?您尚未指定 12,000 多个文件的外观。

标签: bash macos terminal file-structure


【解决方案1】:

给定这样的目录结构:

$ ls /tmp/stacktest
    \textures  
    \textures\actors\bear
        fur.png
    \textures\actors\bear\fur2.png

下面的python脚本会把它变成这样:

$ ls /tmp/stackdest
    textures/actors/bear
        fur.png
        fur2.png

Python 脚本:

from os import walk
import os

# TODO - Change these to correct locations
dir_path = "/tmp/stacktest"
dest_path = "/tmp/stackdest"

for (dirpath, dirnames, filenames) in walk(dir_path):
    # Called for all files, recu`enter code here`rsively
    for f in filenames:
        # Get the full path to the original file in the file system
    file_path = os.path.join(dirpath, f)

        # Get the relative path, starting at the root dir
        relative_path = os.path.relpath(file_path, dir_path)

        # Replace \ with / to make a real file system path
        new_rel_path = relative_path.replace("\\", "/")

        # Remove a starting "/" if it exists, as it messes with os.path.join
        if new_rel_path[0] == "/":
            new_rel_path = new_rel_path[1:]
        # Prepend the dest path
        final_path = os.path.join(dest_path, new_rel_path)

        # Make the parent directory
        parent_dir = os.path.dirname(final_path)
        mkdir_cmd = "mkdir -p '" + parent_dir + "'"
        print("Executing: ", mkdir_cmd)
        os.system(mkdir_cmd)

        # Copy the file to the final path
        cp_cmd = "cp '" + file_path + "' '" + final_path + "'"
        print("Executing: ", cp_cmd)
        os.system(cp_cmd)

脚本读取dir_path 中的所有文件和文件夹,并在dest_path 下创建一个新的目录结构。确保不要将dest_path 放在dir_path 中。

【讨论】:

    猜你喜欢
    • 2015-08-25
    • 1970-01-01
    • 1970-01-01
    • 2018-12-10
    • 2020-11-02
    • 1970-01-01
    • 2011-05-04
    • 2012-05-02
    • 1970-01-01
    相关资源
    最近更新 更多