按文件类型对目录树进行分区

时间:2017-09-03 16:04:48

标签: bash shell

我有一个目录树,其中包含混合了扩展名的文件:

parent/
└── child1
    └── child2
        ├── A.1
        ├── B.1
        └── C.2

我想根据扩展名将目录分成两个单独的目录,例如:

parent.1/
└── child1
    └── child2
        ├── A.1
        └── B.1

和...

parent.2/
└── child1
    └── child2
        └── C.2

只要有两个唯一的树,父目录最终被调用并不重要。我只期待两种不同的文件扩展名。

有人能帮忙吗?

2 个答案:

答案 0 :(得分:3)

find + mkdir + mv算法( bash 变量替换):

我们说我们有以下parent目录树:

parent/
└── child1
    └── child2
        ├── A.1
        ├── B.1
        ├── C.2
        └── D.3

工作:

for f in $(find parent/ -type f); do 
    ext="${f##*.}"      # extracting file extension
    new_path="${f#*/}"  # preparing new file path
    mkdir -p "parent.$ext/${new_path%/*}"  # creating directory with crucial prefix
    mv "$f" "parent.$ext/$new_path"
done

查看结果:

tree parent.[0-9]

输出:

parent.1
└── child1
    └── child2
        ├── A.1
        └── B.1
parent.2
└── child1
    └── child2
        └── C.2
parent.3
└── child1
    └── child2
        └── D.3

答案 1 :(得分:2)

可能是这样的:

  • 查找每个文件,扩展名为" .ext2"在parent1树中。
  • 确保parent2
  • 中存在目录路径
  • 将文件移到那里。

parent1="/path/to/parent1"
pushd "$parent1"
find . -type f -iname "*.ext2" | while read filename; do
    mkdir -p "../parent2/$(dirname "$filename")"
    mv "$filename" "../parent2/$filename"
done
popd
相关问题