bash - 递归地将子文件夹中的文件夹移动到其父文件夹
问题描述
我有一个主文件夹(称为 0 级),其中包含 50 多个子文件夹(1 级),这些子文件夹由较低级别的子文件夹和文件(2 级)组成。我需要将每个文件夹及其内容从 2 级移动到它的 1 级子文件夹(或相对地,它的父文件夹)。
为了更好地可视化这一点:
Master folder
├ Parent Folder A
│ ├─ Subfolder A
│ │ ├─ File A
│ │ └─ File B
│ ├─ Subfolder B
│ │ ├─ File C
│ │ └─ Folder D
.
. ... more folders ...
.
└─ Parent folder 134
├─ Subfolder CS
│ ├─ File AGF
│ └─ File ARH
├─ File ROQ
└─ File JGL
我需要将父文件夹中的文件夹及其文件移动到主文件夹
客观的:
Master folder
├─ Subfolder A
│ ├─ File A
│ ├─ File B
│ ├─ File C
│ ├─ File D
│ ├─ File E
│ └─ File F
├─ Subfolder B
│ ├─ File AZA
│ ├─ File AZB
│ ├─ File AZC
│ └─ File AZD
... and so on
这里的问题是有数百个父文件夹和子文件夹,并且它们都有可能更改的不同名称。它们的数量也可能发生变化。我不知道从哪里开始。我需要在 bash 脚本中执行此操作,虽然我发现其他人已经这样做了,但他们都是在 powershell 中完成的。感谢任何人都可以提供的任何帮助。
解决方案
如果我没看错,您希望每个文件夹下的每个文件都从任何子文件夹中移出,直到主文件夹下的第一个文件夹。
一个简单的版本可能如下所示:
$: find # starting test structure
.
./a
./a/a.txt
./a/e
./a/e/ae.txt
./a/f
./a/f/af.txt
./a/g
./a/g/ag.txt
./b
./b/b.txt
./b/e
./b/e/be.txt
./b/f
./b/f/bf.txt
./b/g
./b/g/bg.txt
./c
./c/c.txt
./c/e
./c/e/ce.txt
./c/f
./c/f/cf.txt
./c/g
./c/g/cg.txt
$: for f in $PWD/*/; # for all the subdirectories in the base folder
> do find $f -type f | xargs -Ithis mv this "$f/"; # move all files up to that sub
> for d in "$f"/*/; do rm -fr "$d"; done; # and remove all lower empty subs
> done
$: find # result
.
./a
./a/a.txt
./a/ae.txt
./a/af.txt
./a/ag.txt
./b
./b/b.txt
./b/be.txt
./b/bf.txt
./b/bg.txt
./c
./c/c.txt
./c/ce.txt
./c/cf.txt
./c/cg.txt
编辑
我认为移动子目录会使它变得容易得多...
$: for b in ./*/*/; do cp -r "$b" ./; rm -fr "$b"; done
$: find
.
./a
./a/a.txt
./b
./b/b.txt
./c
./c/c.txt
./e
./e/ae.txt
./e/be.txt
./e/ce.txt
./f
./f/af.txt
./f/bf.txt
./f/cf.txt
./g
./g/ag.txt
./g/bg.txt
./g/cg.txt
请注意,在我的测试中,我在 a、b 和 c 下都有 e、f 和 g,因此文件收集到了单个新的 2 级目录中。如果在类似名称的目录中有任何同名的文件,您将获得最后一个进程。
推荐阅读
- python - oauth2client.contrib.flask_util 库
- python - 将python与drupal集成
- javascript - 两个不同的 Javascript 文件在两个不同的按钮上执行
- python - tf.fake_quant_with_min_max_args 和 tf.fake_quant_with_min_max_vars 有什么区别
- java - Math.incrementExact(int a)
- list - 我可以创建一个将一些字符串放入元组或列表中的 Haskell 函数吗?
- python - python字数频率中的“名称'word_tokenize'未定义”
- java - Gradle 构建文件在 2.10 版中工作正常,但在升级到 4.6 后它停止工作
- python - Python 读取文件由分隔符确定 \r\n
- python - 编码器/解码器模型如何在深度学习中学习?