我在同一目录(Objects)中有一系列目录(Obj1,Obj2 ......等)。每个Obj目录都包含一些文件。我想在每个Obj中创建一个名为GroupA的文件夹,并将Obj目录中的所有文件放入Group A目录中。我知道如何在单独的文件和目录上执行mkdir和mv,但是如何遍历目录并在所有目录上执行。
初始文件结构应该如下所示
Object --> Object1 __|--> file1
|--> file2
|--> file3
--> Object2 __|--> file1
|--> file2
|--> file3
......
安排后的最终文件结构应如下所示
Object --> Object1 __|--> GroupA __|--> file1
|--> file2
|--> file3
--> Object2 __|--> GroupA __|--> file1
|--> file2
|--> file3
......
感谢。
答案 0 :(得分:1)
经过一些修改后,这个脚本可以为你完成工作,我习惯用它按类型(mp3,wav等)来安排我的歌曲
首先获取主目录(Object)中的所有子目录,然后通过将每个文件或目录移动到先前创建的ObjectA来继续每个子目录
#!/bin/bash
#loop over Object sub directories
#tail is used to delete the first line of find output (Object/)
for SUBDIR in `find $1 -maxdepth 1 -type d | tail -n +2` ;
do
OBJA="${SUBDIR}/ObjA"
mkdir -p $OBJA
#loop over subdirectory (eg Object1) content
for j in `find $SUBDIR -maxdepth 1 | tail -n +2` ;
do
#Here you can add tests to choose which files you want to copy to the new created dir
#This test is to avoid copying ObjectA to it self
[[ "$j" != "$OBJA" ]] && mv $j $OBJA/
done
done
ps:别忘了检查权限:))
答案 1 :(得分:0)
find Object/ -maxdepth 1 -mindepth 1 -type d -exec mkdir \{\}/GroupA \; -exec mv \{\}/* \{\}/GroupA/ \;
可能会对你有用,但它会在尝试将新创建的GroupA
目录移动到自身时给你一条错误消息。
我建议先运行它,如:
find Object/ -maxdepth 1 -mindepth 1 -type d -exec echo mkdir \{\}/GroupA \; -exec echo mv \{\}/* \{\}/GroupA/ \;
(因为这样它会回应它会做什么,如果你对结果感到满意,你可以省略echo
s)
说明:
find Object/
在此目录中搜索-maxdepth 1
目录中只有一个目录-mindepth 1
但目录中至少有一个目录(因此Object
不会包含在搜索结果中)-type d
仅限目录-exec mkdir \{\}/GroupA \;
在(GroupA
部分)中创建\{\}/
目录-exec mv \{\}/* \{\}/GroupA/ \;
并将所有内容从找到的目录移至新创建的GroupA
目录