Ido*_*dos 10 directory recursive directory-structure mv
我有这种通过解压缩 zip 文件获得的目录树:
x -> y -> z ->运行-> 文件和目录在这里
所以有4个目录,其中3个没有文件(x,y,z)并且只包含1个子目录,还有我感兴趣的目录,名为“ run ”。
我想将“运行”目录本身(包括其中的所有内容)移动到我解压缩的“根”位置(即“x”所在的位置,但不在“x”内)。
假设:存在一个名为“run”的文件夹,但我不知道我需要“cd”多少个目录才能到达它(可能是 3 (x,y,z),可能是 10 个或更多。名称也是未知的,不必是 x、y、z 等)。
我怎样才能做到这一点?我尝试了这个问题的许多变体,但都失败了。
Arc*_*mar 14
关于什么
find . -type d -name run -exec mv {} /path/to/X \;
Run Code Online (Sandbox Code Playgroud)
在哪里
(在旁注中有一个--junk-paths
zip 选项,无论是在压缩还是解压缩时)
我会做这bash
,使用globstar
。如中所述man bash
:
globstar
If set, the pattern ** used in a pathname expansion con?
text will match all files and zero or more directories
and subdirectories. If the pattern is followed by a /,
only directories and subdirectories match.
Run Code Online (Sandbox Code Playgroud)
因此,要将目录移动run
到顶级目录x
,然后删除其余目录,您可以执行以下操作:
shopt -s globstar; mv x/**/run/ x/ && find x/ -type d -empty -delete
Run Code Online (Sandbox Code Playgroud)
该shopt
命令启用该globstar
选项。在mv x/**/run/ x/
将命名任何子目录移动run
(注意,如果只有一个这仅适用run
目录)x
和find
将删除任何空目录。
如果你愿意,你可以在 shell 中使用扩展的 globbing 完成整个事情,但我更喜欢安全网,find -empty
以确保没有非空目录被删除。如果你不关心这个,你可以使用:
shopt -s globstar; shopt -s extglob; mv x/**/run/ x/ && rm -rf x/!(run)
Run Code Online (Sandbox Code Playgroud)
绝对更冗长,但只需一步即可完成工作:
#!/usr/bin/env python3
import shutil
import os
import sys
dr = sys.argv[1]
for root, dirs, files in os.walk(dr):
# find your folder "run"
for pth in [d for d in dirs if d == sys.argv[2]]:
# move the folder to the root directory
shutil.move(os.path.join(root, pth), os.path.join(dr, pth))
# remove the folder (top of the tree) from the directory
shutil.rmtree(os.path.join(dr, root.replace(dr, "").split("/")[1]))
Run Code Online (Sandbox Code Playgroud)
get_folder.py
使用根目录(包含解压缩的内容)和要“提升”的文件夹名称作为参数运行它:
python3 /full/path/to/get_folder.py /full/path/to/folder_containing_unzipped_dir run
Run Code Online (Sandbox Code Playgroud)它完成了: