如何使用命令行组合数百个文件夹

Tot*_*ius 2 filesystem command-line directory merge

我有 535 个文件夹(recup_dir.1, recup_dir.2, ..., recup_dir.535),我想将这些文件夹的内容合并(合并?)到一个文件夹中(比如说一个名为 的文件夹recup_dir)。某些文件可能具有相同的名称(例如img.jpg),它们不应覆盖现有文件(而是应将它们重命名为类似img1.jpgimg2.jpg等等...)。

有没有办法使用命令行来做这样的事情?

Jac*_*ijm 5

下面的脚本将包含 535 个文件夹的一个目录中的所有文件(递归地)移动到另一个(单个)目录中,并保留其原始文件名。

如果有重复

(只)重名的情况下,文件将被重新命名为duplicate_1_[filename]duplicate_2_[filename]等等。

如何使用

将下面的脚本复制到一个空文件中,另存为rearrange.py,设置源和目标(目录)的正确路径并通过以下方式运行它:

python rearrange.py
Run Code Online (Sandbox Code Playgroud)

剧本:

#!/usr/bin/env python

import os
import shutil

# --------------------------------------------------------
reorg_dir = "/path/to/sourcedirectory"
target_dir = "/path/to/destination" 
# ---------------------------------------------------------
for root, dirs, files in os.walk(reorg_dir):
    for name in files:
        subject = root+"/"+name
        n = 1; name_orig = name
        while os.path.exists(target_dir+"/"+name):
            name = "duplicate_"+str(n)+"_"+name_orig; n = n+1
        newfile = target_dir+"/"+name; shutil.move(subject, newfile)
Run Code Online (Sandbox Code Playgroud)

对于(gnome-)终端-“拖放”功能:

使用以下版本,按上述方式保存(但不要更改任何内容)并使其可执行。要使用它,请打开一个终端窗口,将脚本拖到终端窗口上,然后是源目录,最后是目标。然后您将在终端中看到的命令:

rearrange.py /path/to/source /path/to/destination
Run Code Online (Sandbox Code Playgroud)

按回车就完成了。

剧本:

#!/usr/bin/env python

import os
import shutil
import sys
# --------------------------------------------------------
reorg_dir = sys.argv[1]
target_dir = sys.argv[2]
# ---------------------------------------------------------
for root, dirs, files in os.walk(reorg_dir):
    for name in files:
        subject = root+"/"+name
        n = 1; name_orig = name
        while os.path.exists(target_dir+"/"+name):
            name = "duplicate_"+str(n)+"_"+name_orig; n = n+1
        newfile = target_dir+"/"+name; shutil.move(subject, newfile)
Run Code Online (Sandbox Code Playgroud)

复制而不是移动

如果您想保持当前目录不变并且只文件复制到新目录中,只需替换最后一行(部分):

代替:

shutil.move(subject, newfile)
Run Code Online (Sandbox Code Playgroud)

经过:

shutil.copy(subject, newfile)
Run Code Online (Sandbox Code Playgroud)